提交后模型为空

时间:2013-11-16 22:23:33

标签: asp.net-mvc-4

我想知道为什么ContactController中的ContactModel没有填充表单中提供的值。我的头在哪里爆炸?

代码原样:

HomeController(联系表格所在的位置)

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var viewModel = new HomeViewModel();
        return View(viewModel);
    }
}

ViewModel for Home

public class HomeViewModel
{
    public ContactModel ContactModel { get; set; }
}

ContactModel保存值

public class ContactModel
{
    [Required(ErrorMessage = "Required")]
    public String Name { get; set; }

    [EmailAddress]
    [Required(ErrorMessage = "Required")]
    public String Email { get; set; }

    [Required(ErrorMessage = "Required")]
    public String Message { get; set; }
}

HomeController的索引视图

@model MyNameSpace.ViewModels.HomeViewModel

@using (Html.BeginForm("Send", "Contact", FormMethod.Post))
{
    <div class="form-group">
        @Html.LabelFor(model => model.ContactModel.Name, "Name", new { @class = "sr-only" })
        @Html.TextBoxFor(model => model.ContactModel.Name, new { @class = "form-control", @placeholder = "Name" })
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.ContactModel.Email, "E-mail", new { @class = "sr-only" })
        @Html.TextBoxFor(model => model.ContactModel.Email, new { @class = "form-control", @placeholder = "E-mail" })
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.ContactModel.Email, "Message", new { @class = "sr-only" })
        @Html.TextAreaFor(model => model.ContactModel.Message, new { @class = "form-control", @placeholder = "Message" })
    </div>
    <p><button type="submit" class="btn btn-default">Send</button></p>
}

ContactController发送

public class ContactController : Controller
{
    [HttpPost]
    public ActionResult Send(ContactModel model)
    {
        if (ModelState.IsValid)
        {
            // ModelState is not valid - but why!?
            return RedirectToAction("Index", "Success");
        }

        return RedirectToAction("Index", "Error");

    }

}

由于某些原因我的表单提交,ContactController.Send(ContactModel model)中提供的模型都具有所有空值 - 链接断开的位置在哪里?

1 个答案:

答案 0 :(得分:1)

您的POST操作应将视图模型作为参数而不是域模型:

[HttpPost]
public ActionResult Send(HomeViewModel model)

原因很简单 - 这是默认模型绑定器的工作方式。视图中的输入字段都以ContactModel为前缀。

或者,您可以使用Bind属性并明确指定:

[HttpPost]
public ActionResult Send([Bind(Prefix = "ContactModel")] ContactModel model)