控制器发布操作无法捕获对象列表 [英] controller post action not able catch list of objects
问题描述
它可能重复了一个问题,我搜索了所有内容,但不满意,所以我在这里发布问题.
It may duplicate question, i have searched all over but couldn't satisfied, so i am posting here question.
我有一个对象(从实体框架生成),
I have object as (generated from entity framework),
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);
}
提交表单控制器后,列表的值变为空值,代码有什么问题?
After submitting the form controller gets null value for list, what is wrong with code??
推荐答案
您不能使用.ElementAt()
.如果检查生成的html,您会看到name
属性与您的模型没有关系.
You cannot use .ElementAt()
. If you inspect the html your generating you will see that the name
attribute has no relationship to your model.
您的模型需要实现IList<Usp_Sel_NotEnteredStringResources_Result>
并使用for
循环
You model needs to implemet IList<Usp_Sel_NotEnteredStringResources_Result>
and use a for
loop
@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<Usp_Sel_NotEnteredStringResources_Result>
,则可以使用EditorTemplate
(请参考[
Alternative if the model is IEnumerable<Usp_Sel_NotEnteredStringResources_Result>
, you can use an EditorTemplate
(refer [Post an HTML Table to ADO.NET DataTable for more details on how the name
attributes must match your model property names, and the use of an EditorTemplate
)
这篇关于控制器发布操作无法捕获对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!