Model is null on HttpPost

This one has me utterly baffled...

I have a very simple input model, with three string properties like so:

public class SystemInputModel
{
    public string Name;
    public string Performance;
    public string Description;
}

In my controller:

public ViewResult AddSystem()
{
    return View(new SystemInputModel());
}


[HttpPost]
public ActionResult AddSystem(SystemInputModel model) 
{
    if (ModelState.IsValid)
    {
        var system = new OasisSystem
        {
            Name = model.Name,
            Description = model.Description,
            Performance = model.Performance
        };
        return Json(repository.AddSystem(system));
    }
    return Json(new {success = false, message = "Internal error"});
}

The view:

<h2>Add System</h2>

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)
    <label>Name</label>
    @Html.EditorFor(m => m.Name)
    <br />
    <label>Description</label>
    @Html.EditorFor(m => m.Description)
    <br />
    <label>Performance</label>
    @Html.EditorFor(m => m.Performance)
    <br />

    <input type="submit" />
}

I fill in the form fields and hit submit. I've looked at the raw Post in Fiddler:

POST http://localhost.:4772/System/AddSystem HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Referer: http://localhost.:4772/System/AddSystem
Accept-Language: en-us
Content-Type: application/x-www-form-urlencoded
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E; MS-RTC LM 8)
Connection: Keep-Alive
Content-Length: 42
Host: localhost.:4772
Pragma: no-cache
Cookie: ASP.NET_SessionId=5i4jtrrhjuujvtbpsju4bu3f

Name=foo&Description=bar&Performance=yes

However, the model that is being passed into my HttpPost controller method has null values for all three properties. If I change it from my model object to FormCollection, I can see the three properties passed in.

Why aren't the posted fields being mapped to my model object?


The default MVC 3 model binder requires properties on your models.

If you change your model to this:

public class SystemInputModel
{
    public string Name { get; set; }
    public string Performance { get; set; }
    public string Description { get; set; }
}

All will be well.

链接地址: http://www.djcxy.com/p/53958.html

上一篇: MVC文本框回发问题

下一篇: HttpPost上的模型为空