为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
FFIVE 2023-07-09 15:25:46
我在 _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);能做到吗?我将如何处理这个问题?谢谢!
查看完整描述

3 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

生成 html 时会消耗 razor 属性。如果您从 javascript 引用此内容,则需要一个在页面编译后保留的属性。这对于您的情况来说很棘手,因为您试图在请求完成后具体化路线。


相反,将输入值传递给操作的良好语义方式是使用表单,而不是尝试动态构建锚点。


<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>


查看完整回答
反对 回复 2023-07-09
?
函数式编程

TA贡献1807条经验 获得超9个赞

通过在 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" 

data-producttypeId="@product.ProductTypeId">

}

我添加了一个 jQuery 函数:


$('.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;

});

对字符串的替换会创建一个新字符串,而不是实际替换它。将新创建的字符串放入 href 后,一切都很好!感谢大家的意见,给了我一些很好的线索!


查看完整回答
反对 回复 2023-07-09
?
ITMISS

TA贡献1871条经验 获得超8个赞

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 中


 $("#productCard").click(function (e) {

            // Stop the normal navigation

            e.preventDefault();


            //Build the new URL

            var url = $(this).attr("href");

            var date = $("#cropIdForProdBaseJQ").val();

            url = url.replace(1, date);


            //Navigate to the new URL

            window.location.href = url;


        });


查看完整回答
反对 回复 2023-07-09
  • 3 回答
  • 0 关注
  • 91 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信