我有一个简单的模型如下:
public class MyRecordModel
{
public MyRecordModel()
{
}
public string Name{ get; set; }
public string Surname { get; set; }
public string Email { get; set; }
}
然后我有它的编辑模型:
public partial class MyRecordEditModel
{
public MyRecordEditModel()
{
this.MyRecord= new MyRecordModel();
}
public MyRecordModel MyRecord { get; set; }
}
控制器也很简单:
public ActionResult MyRecordAdd()
{
var model = new MyRecordEditModel();
return View(MYROUTE, model);
}
[HttpPost]
public ActionResult MyRecordAdd(MyRecordEditModel model)
{
if (ModelState.IsValid)
{
//Save to db
}
}
这是我的观点:
@model MyRecordEditModel
@using (Html.BeginForm())
{
@Html.HiddenFor(model => model.MyRecord.Id)
<table>
<tr>
<td>
@Html.LabelFor(model => model.MyRecord.Name):
</td>
<td>
@Html.EditorFor(model => model.MyRecord.Name)
@Html.RequiredHint()
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.MyRecord.Surname)
</td>
<td>
@Html.EditorFor(model => model.MyRecord.Surname)
@Html.RequiredHint()
</td>
</tr>
<tr>
<td>
@Html.LabelFor(model => model.MyRecord.Email):
</td>
<td>
@Html.EditorFor(model => model.MyRecord.Email)
@Html.RequiredHint()
</td>
</tr>
</table>
<div class="buttons">
<input type="submit" value="@T("Common.Save")" />
</div>
}
从视图返回的模型始终为空。但是,如果我使用FormCollection而不是模型,则会正确填充字段。
问题是什么?
答案 0 :(得分:1)
就我个人而言,我不想使用FormCollection
,而是值应该为Model
获取值。我认为你应该采用自定义模型绑定方法。查看ModelBinding
的链接。
http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspx http://buildstarted.com/2010/09/12/custom-model-binders-in-mvc-3-with-imodelbinder/