MVC4视图模型总是空的[HttpPost]

本文关键字:HttpPost 视图 模型 MVC4 | 更新日期: 2023-09-27 18:15:03

我有一个简单的模型如下:

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而不是模型,则字段将被正确填充。

有什么问题吗?

MVC4视图模型总是空的[HttpPost]

我个人不喜欢使用FormCollection,而是值应该得到Model的值。我认为你应该使用自定义模型绑定方法。查看ModelBinding的给定链接。

http://dotnetslackers.com/articles/aspnet/Understanding-ASP-NET-MVC-Model-Binding.aspxhttp://buildstarted.com/2010/09/12/custom-model-binders-in-mvc-3-with-imodelbinder/