【问题标题】:controller post action not able catch list of objects控制器发布操作无法捕获对象列表
【发布时间】:2017-05-12 12:38:25
【问题描述】:

它可能会重复问题,我已经搜索过但不满意,所以我在这里发布问题。

我有对象(从实体框架生成),

 public partial class Usp_Sel_NotEnteredStringResources_Result
{

    public string name { get; set; }
    public Nullable<int> Value { get; set; }

    public int StringResourceId { get; set; }
    public Nullable<int> LanguageId { get; set; }
} 

和我创建的视图,

@{
    ViewBag.Title = "Resource Entry Languagewise";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>ResourceEntry</h2>

@using (Html.BeginForm("ResourceEntry", "LangResource", FormMethod.Post))
{

   <fieldset>
<table>


 @for (int i = 0; i < Model.ToList().Count; i++)
 {
       <tr>
        <td>@Html.DisplayFor(m => Model.ElementAt(i).name)</td>
        <td>@Html.TextBoxFor(m => Model.ElementAt(i).Value)</td>

           @Html.HiddenFor(m => Model.ElementAt(i).LanguageId)
           @Html.HiddenFor(m => Model.ElementAt(i).name)
           @Html.HiddenFor(m => Model.ElementAt(i).StringResourceId)                 
    </tr> 
 }

</table>
       <p>
            <input type="submit" value="Save" />
        </p>
          </fieldset>
}

和控制器一样,

 [HttpPost]
        public ActionResult ResourceEntry(List<Usp_Sel_NotEnteredStringResources_Result> list)
        {
           // here getting the null value for list
            // ??????  
            return View(list);
        }

表单控制器提交后得到列表的空值,代码有什么问题??

【问题讨论】:

    标签: entity-framework asp.net-mvc-4 razor


    【解决方案1】:

    您不能使用.ElementAt()。如果您检查生成的 html,您将看到 name 属性与您的模型无关。

    您的模型需要实现 IList&lt;Usp_Sel_NotEnteredStringResources_Result&gt; 并使用 for 循环

    @for (int i = 0; i < Model.Count; i++)
    {
        <tr>
            <td>@Html.DisplayFor(m => m[i].name)</td>
            <td>
                @Html.TextBoxFor(m => m.[i]Value)
                // note you hidden inputs should be inside a td element
                @Html.HiddenFor(m => m[i].LanguageId)
                ....
            </td>             
        </tr>
    }
    

    如果模型是 IEnumerable&lt;Usp_Sel_NotEnteredStringResources_Result&gt;,您可以使用 EditorTemplate(请参阅 [Post an HTML Table to ADO.NET DataTable 了解更多关于 name 属性必须如何匹配您的模型属性名称以及使用 EditorTemplate )

    【讨论】:

    • @for (int i = 0; i
    • 好的,我实现了 IList 而不是 IEnumerable,现在我得到了建议 Count
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多