1

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

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

问题可能是什么?

4

1 回答 1

1

就我个人而言,我不想使用FormCollectionvalues 应该将值改为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/

于 2013-05-24T07:19:09.087 回答