Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use hiddenfield-value for asp-route-parameter

Ive got a hidden field in a _PartialView with the value I want (jQuery fills it up) I need this same value in a (foreach) asp-route-parameter

<div class="js-products-list">
 <input id="cropIdForProdBaseJQ" type="hidden" value="" />
  @foreach (var product in Model.Products)
  {
    <a asp-controller="XXX" asp-action="YYY" asp-route-language="@Model.CurrentLanguage" asp-route-cropId="" id="productCard">
  }

So, asp-route-cropId should get the value from the hiddenfield, to pass it along as parameter

I tried using a jQueryfunction (without any luck) like

var neededValue = the value I got from another jQfunction
$('#productCard').attr("asp-route-cropId", neededValue);

Can it be done?
How would i approach this? Thanks!

like image 894
BHANG Avatar asked Oct 30 '25 04:10

BHANG


2 Answers

The razor attributes are consumed when the html is generated. If you're referencing this from javascript you would need an attribute that persists after the page is compiled. This is tricky in your case because you're trying to materialize a route after the request has completed.

Instead, the nice semantic way of passing input values to actions is with a form instead of trying to build an anchor dynamically.

<form method="get" asp-controller="XXX" asp-action="YYY" asp-route-language="@Model.CurrentLanguage">
    <input id="cropIdForProdBaseJQ" type="hidden" value="" />
    @foreach (var product in Model.Products)
    {
        @* Assuming you are doing something useful with "product" here *@
        <button name="PassThisId" value="@product.ProductId">Press me!</button>
    }
</form>
like image 110
James Sampica Avatar answered Nov 01 '25 19:11

James Sampica


Solved this by adding a data-producttypeId in the a-tag; changed productCard from 'id' to 'class'

@foreach (var product in Model.Products)

{
<a asp-controller="XXX" asp-action="YYY" asp-route-language="@Model.CurrentLanguage" asp-route-cropId="" class="productCard" 
data-producttypeId="@product.ProductTypeId">
}

I added a jQuery function:

$('.productCard').click(function(e) {    
var cropId = $('#croptype-filter-From-ProductType').val();

var clickedCard = $(this);
var baseUrl = clickedCard.attr("href");

var newUrl = baseUrl.replace("crop-ID", cropId);
window.location.href = newUrl;
});

A replace on a string creates a new string instead of actually replacing it. After placing the newly created string in the href, all was good! Thanks for the input guys, gave me some good leads!

like image 28
BHANG Avatar answered Nov 01 '25 17:11

BHANG