【问题标题】:.Net MVC 4 How to get array in Model or from Form Collection on form submit.Net MVC 4 如何在模型中获取数组或从表单集合中获取表单提交
【发布时间】:2015-04-06 05:14:21
【问题描述】:

我正在使用 .net MVC 4 我的问题是我有多个具有相同名称的输入控件,后缀为 0、1、2,如数组。我想要一个对象或对象列表中的所有这些值。我的视图(Razor,.cshtml) 中的控件如下所示:

<input type="hidden" value="FirstName" name="MyListData[0]" id="MyListDataUnSelected_0_">
<input type="hidden" value="MiddleName" name="MyListData[1]" id="MyListDataUnSelected_1_">
<input type="hidden" value="LastName" name="MyListData[2]" id="MyListDataUnSelected_2_">

我在控制器上的 post 方法是这样的:

public ActionResult Index(List<string> MyListData, FormCollection pFormCollection)

从集合中它给了我 MyListData[0],MyListData[1],... 的值 但 List MyListData 为空。我在应用相同的代码中还有另一个页面,在这种情况下,我会在 MyListData 中获得值列表。

我也试过使用 string[] MyListData 但还是不行。

如何在模型或表单集合中获取该列表。

【问题讨论】:

  • 只是一个疯狂的猜测。如果您从操作中删除 pFormCollection 参数并仅保留 MyListData 会发生什么?
  • 您是否通过 razor helper @Html.TextBoxFor&lt;&gt; 生成输入?
  • 不,我只使用了 控件,因为它们是使用 jquery 创建的。
  • @DixonD 如果我删除 pFormCollection 则 MyListData 也仅为空。
  • 使用 Firebug 或类似的,您是否能够观察到实际发布的值?您可能还想尝试安装 Glimpse。

标签: c# .net asp.net-mvc-4 razor formcollection


【解决方案1】:

我目前的解决方案是

List<string> lststr=new List<string>();
int i=0;
while(true)
{
    if(pFormCollection["MyListData[" + i + "]"]!=null)
    {
         lststr.add(pFormCollection["MyListData[" + i + "]"]);
         i++;
    }
    else
        break;
}

简而言之

List<string> lststr=new List<string>();
int i=0;
while(pFormCollection["MyListData[" + i + "]"]!=null)
{

         lststr.add(pFormCollection["MyListData[" + i + "]"]);
         i++;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2012-06-12
    • 2014-03-23
    • 1970-01-01
    • 2014-04-17
    相关资源
    最近更新 更多