对 asp-route-parameter 使用隐藏字段值

我在 _PartialView 中有一个隐藏字段,其中包含我想要的值(jQuery 填充它)我需要在(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">

  }

因此,asp-route-cropId 应该从隐藏字段获取值,并将其作为参数传递


我尝试使用 jQueryfunction (没有任何运气)像


var neededValue = the value I got from another jQfunction

$('#productCard').attr("asp-route-cropId", neededValue);

能做到吗?

我将如何处理这个问题?谢谢!


FFIVE
浏览 92回答 3
3回答

BIG阳

生成 html 时会消耗 razor 属性。如果您从 javascript 引用此内容,则需要一个在页面编译后保留的属性。这对于您的情况来说很棘手,因为您试图在请求完成后具体化路线。相反,将输入值传递给操作的良好语义方式是使用表单,而不是尝试动态构建锚点。<form method="get" asp-controller="XXX" asp-action="YYY" asp-route-language="@Model.CurrentLanguage">&nbsp; &nbsp; <input id="cropIdForProdBaseJQ" type="hidden" value="" />&nbsp; &nbsp; @foreach (var product in Model.Products)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; @* Assuming you are doing something useful with "product" here *@&nbsp; &nbsp; &nbsp; &nbsp; <button name="PassThisId" value="@product.ProductId">Press me!</button>&nbsp; &nbsp; }</form>

函数式编程

通过在 a 标签中添加 data-producttypeId 解决了这个问题;将productCard从“id”更改为“class”@foreach (var product in Model.Products){<a asp-controller="XXX" asp-action="YYY" asp-route-language="@Model.CurrentLanguage" asp-route-cropId="" class="productCard"&nbsp;data-producttypeId="@product.ProductTypeId">}我添加了一个 jQuery 函数:$('.productCard').click(function(e) {&nbsp; &nbsp;&nbsp;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;});对字符串的替换会创建一个新字符串,而不是实际替换它。将新创建的字符串放入 href 后,一切都很好!感谢大家的意见,给了我一些很好的线索!

ITMISS

razor 视图中的标签助手在服务器上执行,其结果(HTML 标记)将发送到浏览器,浏览器将呈现它。所以此时anhcor tag helper已经生成了链接的href属性值。您可以做的是,使用 JavaScript 覆盖正常的链接单击行为,从页面读取输入元素值,并使用它构建新的 URL 并导航到该值。您可以为您的 CropId 参数指定一个虚拟值。<a asp-controller="invoices" asp-action="GetData" asp-route-name="@Model.supplierName" asp-route-cropId=1 id="productCard">Click me</a>在 JavaScript 中&nbsp;$("#productCard").click(function (e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Stop the normal navigation&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Build the new URL&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var url = $(this).attr("href");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var date = $("#cropIdForProdBaseJQ").val();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url = url.replace(1, date);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //Navigate to the new URL&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; window.location.href = url;&nbsp; &nbsp; &nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP