Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16330

MVC4 Viewmodel always empty on [HttpPost]

I have a simple model as follows:

public class MyRecordModel
{
    public MyRecordModel()
    {
    }

    public string Name{ get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
}

Then I have the its edit model:

public partial class MyRecordEditModel
{
    public MyRecordEditModel()
    {
        this.MyRecord= new MyRecordModel();
    }
    public MyRecordModel MyRecord { get; set; }
}

The controller is also quite simple:

    public ActionResult MyRecordAdd()
    {
        var model = new MyRecordEditModel();
        return View(MYROUTE, model);
    }

    [HttpPost]
    public ActionResult MyRecordAdd(MyRecordEditModel model)
    {
        if (ModelState.IsValid)
        {
            //Save to db
        }
    }

And this is my view:

@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>
}

The model returned from the view is always empty. However, if I use FormCollection instead of the model, the fields are correctly populated.

What can the problem be?

Upvotes: 1

Views: 963

Answers (1)

Satpal
Satpal

Reputation: 133453

Personally I would not like to use FormCollection instead values should get values to Model. I think you should go for Custom Model Binding approach. Check out given link for 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/

Upvotes: 1

Related Questions