[英]Model binding generic list is null in asp.net mvc
I am binding objects in a razor foreach in the index.html: 我在index.html中的razor foreach中绑定对象:
VIEW 视图
@using (Ajax.BeginForm("Save", "Unit", new AjaxOptions { OnSuccess = "onSuccess" }))
{
<button type="submit" class="btn btn-default" id="saveUnits"><i class="fa fa-save"></i></button>
<table>
<tbody>
@foreach (var item in Model)
{
<tr>
@Html.HiddenFor(modelItem => item.UnitId)
<td>
@Html.EditorFor(modelItem => item.Name)
</td>
<td>
@Html.EditorFor(modelItem => item.ErrorText)
</td>
</tr>
}
</tbody>
</table>
}
I have grabbed the data sent to my action parameter with fiddler and got this: 我用fiddler抓住了发送到我的action参数的数据,得到了这个:
item.UnitId=5&
item.Name=111111111111&
item.ErrorText=fsdddddddddddddddd+&
item.UnitId=5&
item.Name=+&
item.ErrorText=dddddd+&
ACTION 行动
public ActionResult Save(List<Unit> units )
{
return new EmptyResult();
}
VIEWMODEL 视图模型
public class Unit
{
[HiddenInput(DisplayValue = false)]
public int UnitId { get; set; }
[DataType(DataType.MultilineText)]
public string Name { get; set; }
[DataType(DataType.MultilineText)]
public string ErrorText { get; set;
}
Why is my units instance null? 为什么我的单位实例为空? The properties match so they should be bound!
属性匹配所以他们应该绑定!
Did I overlook something? 我忽略了什么吗?
You need to use a for
loop not a foreach
loop. 你需要使用
for
循环而不是foreach
循环。 Also, it would be better to make your Model class have a property which is a collection. 此外,最好使您的Model类具有属性集合。
Your model could be something like: 你的模型可能是这样的:
public class UnitsViewModel
{
public List<Unit> Units { get; set; }
public class Unit
{
[HiddenInput(DisplayValue = false)]
public int UnitId { get; set; }
[DataType(DataType.MultilineText)]
public string Name { get; set; }
[DataType(DataType.MultilineText)]
public string ErrorText { get; set; }
}
}
And you could do the following in your cshtml: 你可以在你的cshtml中执行以下操作:
@for (int i = 0; i < Model.Count; i++)
{
<tr>
@Html.HiddenFor(m => m.Units[i].UnitId)
<td>
@Html.EditorFor(m => m.Units[i].Name)
</td>
<td>
@Html.EditorFor(m => m.Units[i].ErrorText)
</td>
</tr>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.