【问题标题】:Pass values from Hidden field to ActionLink then to Controller将值从 Hidden 字段传递给 ActionLink,然后传递给 Controller
【发布时间】:2015-07-13 19:30:39
【问题描述】:

我试图通过让用户选择他们想要的报告的复选框来动态设置 StudentId。当他们单击 ActionLink 时,我使用 jQuery 在隐藏字段中设置 id 的值。我需要操作链接来读取隐藏字段中的 ID。

值在隐藏字段中设置,但它们没有从 actionLink 传递给控制器​​。

我需要将 ReportIds 传递给控制器​​。

        @Html.ActionLink("PrintMed", "GetMedEdVerificationReport", "Student", new { studentIdList = Model.ReportIds }, new { @class = "button print_selected print_selectedMedEd disabled" })



        @Html.HiddenFor(model => model.ReportIds)

javascript

$('.print_selectedMedEd').bind('click', function () {
    var ids = getPrintIds();
    if (ids.length == 0) {
        return false;
    }

    $('#ReportIds').val(ids.toString());


    return true;
});

【问题讨论】:

  • 为什么不发布表单值?
  • 你的控制器动作是什么样的?模型是什么样的?链接的渲染 HTML 是什么样的?当您发出请求时,调试网络监视器中的内容是什么样的?
  • 听起来您只需要创建一个表单,将您的复选框放入表单中,然后只需一个提交按钮即可。否则您的 print_selectedMedEd 需要更新您的 PrintMed 链接中的 url 以包含来自 ids 的值,这似乎太麻烦了

标签: c# asp.net asp.net-mvc asp.net-core razor


【解决方案1】:

当 asp.net mvc 渲染您的 ActionLink 时,它将生成一个链接,其中包含您在模型上拥有的参数。如果您更改模型的值,它不会更改ActionLink 生成的输出上的值。

鉴于此,您必须再次设置值,尝试生成不带参数的 ACtionLink:

@Html.ActionLink("PrintMed", "GetMedEdVerificationReport", "Student", null, new { @class = "button print_selected print_selectedMedEd disabled" })

在 javascript 方面,您可以尝试使用on 方法绑定事件处理程序并从事件参数调用preventDefault 方法,例如:

$('.print_selectedMedEd').on('click', function (e) {
    e.preventDefault();
    var ids = getPrintIds();
    if (ids.length > 0) {
       $('#@Html.IdFor(model => model.ReportIds)').val(ids.toString());

       // make an url to redirect
       var url = $(this).prop("href") + "?studentIdList=" + ids.toString();
       // redirect using the generated url
       window.location.href = url;
    }
});

记得使用Html.IdForm() 来确保您拥有特定属性的正确ID。

【讨论】:

    【解决方案2】:

    那是因为@Html.ActionLink不使用隐藏字段来发出请求。一旦动作链接呈现它就变成 <a href="/Student/GetMedEdVerificationReport/reportIds..."> PrintMed </a> 所以你需要修改锚标签上的html。

    您应该改用 Html.Beginform 来传递模型。

    @using (Html.BeginForm("GetMedEdVerificationReport", "Student", FormMethod.Post, null))
        {
            @Html.HiddenFor(model => model.ReportIds)
            <input type="submit" value="PrintMed" />
        }
    

    【讨论】:

      【解决方案3】:
                   @Html.HiddenFor(modelItem => item.OrderId)
                  <td>
      
                      <input type="button" value="Pickup" onclick="location.href='@Url.Action("Edit", "Assignment", new { ID = item.OrderId })'" />
      

      【讨论】:

      • 您能否提供一些文字来解释您的答案?虽然仅代码的答案在技术上可能是正确的,但它有助于解释为什么代码是正确的解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 2020-02-06
      • 2011-12-10
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多