MVC4没有像预期那样阅读postdata形式.它看到的是单个字段,但不是完整对象

Joh*_*lle 0 c# asp.net-mvc-4

我试图让一个非常简单的项目作为地址阅读器.出于某种原因,当我设置从编辑表单获取Post数据响应的方法时,它只有在我设置它以查找单个变量才能正确读取发布数据但是如果我将其设置为接受复杂项目时失败.

这是我的控制器代码:

[HttpGet]
public ActionResult Index()
{
    ViewBag.Message = "";
    Address address = new Address();
    return View(address);
}


[HttpPost]
//public ActionResult Index(String Name, String Street1, String Street2, String City, String State, String Zip)
public ActionResult Index(Address model)
{
    Address address = model;

    //check ModelState
    if (!ModelState.IsValid)
        return View(address);
    else
    {
        ViewBag.Message = "Save Success";
        address = new Address();
        return Redirect("/");
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我使用注释掉的行,所有这些行都被正确填充,但如果我使用该public ActionResult Index(Address model)行,则模型变量保持为空.

这是我的视图的表单代码:

@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    <fieldset>
        <legend>Your Address</legend>
        <p>@Html.LabelFor(model => model.Name) @Html.TextBoxFor(model => model.Name)</p>
        <p>@Html.LabelFor(model => model.Street1, "Street address:") @Html.TextBoxFor(model => model.Street1, new Dictionary<string, object>{ {"tabindex" , "1"}, {"placeholder","Start typing to get suggestions"}})</p>
        <p>@Html.LabelFor(model => model.Street2, "Street address 2:") @Html.TextBoxFor(model => model.Street2, new Dictionary<string, object>{ {"tabindex" , "2"} })</p>
        <p>@Html.LabelFor(model => model.City, "City:") @Html.TextBoxFor(model => model.City, new Dictionary<string, object>{ {"tabindex" , "3"} })</p>
        <p>@Html.LabelFor(model => model.State, "State:") @Html.TextBoxFor(model => model.State, new Dictionary<string, object>{ {"tabindex" , "4"} })</p>
        <p>@Html.LabelFor(model => model.Zip, "Zip:") @Html.TextBoxFor(model => model.Zip, new Dictionary<string, object>{ {"tabindex" , "5"} })</p>
        <input type="submit" id="submitButton" class="green" tabindex="6" value="Save">
    </fieldset>
}
Run Code Online (Sandbox Code Playgroud)

地址类:

public class Address
{
    public String Name;
    public String Street1;
    public String Street2;
    public String City;
    public String State;
    public String Zip;
}
Run Code Online (Sandbox Code Playgroud)

MRB*_*MRB 5

将您的模型更改为:

public class Address
{
    public String Name { get; set; }
    public String Street1 { get; set; }
    public String Street2 { get; set; }
    public String City { get; set; }
    public String State { get; set; }
    public String Zip { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Mvc 模型绑定器仅适用于复杂类型的属性.