【问题标题】:How to pass HiddenFor value from view to controller如何将 HiddenFor 值从视图传递到控制器
【发布时间】:2016-05-16 18:11:09
【问题描述】:

我有一个视图,其中包含列表中的数据,我将其填充到表中。
查看:

@using (Html.BeginForm("DistrictReport", "Reports", FormMethod.Post))
{
@for(int i = 0; i < Model.Count; i++)
{
<tr>
    <td>
        @Html.DisplayFor(model => Model[i].DISTRICT)
        @Html.HiddenFor(model => Model[i].DISTRICT)
    </td>
    <td>
        <input type="submit" name="submitButton" value="Show Report 1"/>
        <input type="submit" name="submitButton" value="Show Report 2"/>
    </td>
</tr>
}
}

这是我的控制器。
控制器:

public ActionResult DistrictReport(string DISTRICT, string submitButton)
{
  if (submitButton.Contains("Show Report"))
  {
    var district = new SqlParameter
      {         
        ParameterName = "District",
        Value = DISTRICT
      };
enter code here
var list = db.Database.SqlQuery<ReportDistrict>("exec getDistrictNumber @District", district).ToList<ReportDistrict>();
    //.....
  }
}

当我单击提交按钮时,页面会显示警告,即 DISTRICT 值为空。 我需要做的是将 DISTRICT 值输入到控制器中,以便存储过程可以执行。 问题是视图中的每一行都有一个按钮。 这是警告:

'(@District nvarchar(4000))exec getDistrictAndNumber @District' expects the parameter '@District', which was not supplied.

有什么建议吗?任何其他方式也非常受欢迎。

【问题讨论】:

  • 渲染的隐藏字段是什么样的,网络监视器对发布的数据显示什么?
  • 你的视图是一个集合,所以 post 方法也需要是一个集合。 post 方法应该是public ActionResult DistrictReport(List&lt;###&gt; model, string submitButton),其中### 是您在视图中使用的模型。 (或者可以是public ActionResult DistrictReport(string[] DISTRICT, string submitButton)
  • 请不要在标题中添加不必要的关键字——这就是标签的用途。

标签: c# asp.net-mvc view controller


【解决方案1】:

您有多种选择。

  1. 为开始表单使用 html 助手,这将允许您使用表单的详细信息发布到操作,并且您的提交按钮将发布到该操作。

    https://msdn.microsoft.com/en-us/library/dd505244(v=vs.118).aspx

    beginform 接受您指定操作和控制器的参数。提交按钮将自动使用它。

  2. 使用 jQuery 执行一个 ajax 例程,您可以让您作为 ajax url 目标操作,并从 jQuery ajax“数据”值传递控制器的值。使用这种方法,您需要有 id 或 class 以及您的 html 元素,然后您可以在调用 ajax 方法之前使用 jQuery 来获取它。

    http://api.jquery.com/jquery.ajax/

【讨论】:

    【解决方案2】:

    您在操作中使用单个变量,但鉴于有一个地区列表,这就是您必须在下面使用的原因..

    public ActionResult DistrictReport(string[] DISTRICT, string submitButton)
    

    【讨论】:

    • 我试过这个,但仍然没有帮助。我需要更改视图中的任何内容吗?
    猜你喜欢
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 2015-10-03
    相关资源
    最近更新 更多