asp.net-mvc - HttpPost 上的模型为空

标签 asp.net-mvc asp.net-mvc-3

这个让我完全困惑......

我有一个非常简单的输入模型,具有三个字符串属性,如下所示:

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

在我的 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"});
}

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" />
}

我填写表单字段并点击提交。我查看了 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

但是,传递到我的 HttpPost Controller 方法的模型的所有三个属性都为空值。如果我将其从模型对象更改为 FormCollection,我可以看到传入的三个属性。

为什么发布的字段没有映射到我的模型对象?

最佳答案

默认的 MVC 3 模型绑定(bind)器需要模型的属性。

如果您将模型更改为:

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

一切都会好起来的。

关于asp.net-mvc - HttpPost 上的模型为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11837565/

相关文章:

javascript - 使用ajax mvc搜索数据时如何在查询字符串上保留id

c# - 帮助 MVC 3 路由

JavaScript 无法识别 Controller

.net - 在 ASP.NET MVC 控件中放置可重用代码的最佳位置?

.net - Razor View »呈现为»的字符

c# - 忽略无效的 SSL 证书

javascript - MVC4 将所有表单数据(模型)从 javascript 传递到 Controller - 这可能吗?

asp.net-mvc - 如何在mvc中编写分页的扩展方法

asp.net-mvc - 带有 html 实体的 MVC 标签

c# - 没有具有键 xxxxxx 的 'IEnumerable<SelectListItem>' 类型的 ViewData 项