MVC4通过Ajax.BeginForm传递模型

我试图在这里关注一些好的post以使其工作,但每次我点击ajax回发时,我的控制器中的断点显示一个具有空值的模型。 此页面显示仅供查看的模型值,但我已尝试将它们放在自己的表单中,并将它们包装在ajax表单中,似乎没有任何效果。

@model VendorProfileIntranet.Models.VendorProfile $(function () { $("form").submit(function () { if ($(this).valid()) { $.ajax({ url: this.action, type: this.method, data: $(this).serialize(), success: function (result) { $("#message").html(result); } }); } return false; }); 

});

  @using (Ajax.BeginForm("SelectVendor", "Home", new AjaxOptions { HttpMethod="post", InsertionMode=InsertionMode.Replace, UpdateTargetId="message" })) { 

视图非常长(仅显示用于查看的模型值),此处缩写。

 
Contact Information @Html.HiddenFor(model => model.ProfileID)
@Html.LabelFor(model => model.Name) @Html.DisplayFor(model => model.Name)

@Html.LabelFor(model => model.Email) @Html.DisplayFor(model => model.Email)

@Html.LabelFor(model => model.Phone) @Html.DisplayFor(model => model.Phone)

@Html.LabelFor(model => model.Website) @Html.DisplayFor(model => model.Website)

@Html.LabelFor(model => model.CompanyName) @Html.DisplayFor(model => model.CompanyName)

@Html.LabelFor(model => model.Address1) @Html.DisplayFor(model => model.Address1)

@Html.LabelFor(model => model.Address2)  @Html.DisplayFor(model => model.Address2)

@Html.LabelFor(model => model.City) @Html.DisplayFor(model => model.City)

@Html.LabelFor(model => model.State) @Html.DisplayFor(model => model.State)

@Html.LabelFor(model => model.Zip) @Html.DisplayFor(model => model.Zip)

@Html.LabelFor(model => model.VendorNotes)

@Html.DisplayFor(model => model.VendorNotes)


}

控制器。 我已经用一两种forms尝试了上述内容。 使用上面的代码,模型包含除了填充在隐藏输入字段中的ProfileID之外的所有空值。 我认为传递模型应该工作而不必为每个模型值创建隐藏字段?

 [HttpPost] public ActionResult SelectVendor(VendorProfile pageModel) { // handle selected vendor _DAL.SelectVendor(pageModel.ProfileID); return Content("This Vendor has been selected", "text/html"); } 

回答

由于使用了DisplayFor,模型值没有绑定

如评论中所述,您实际上希望在模型中看到使用DisplayFor放入表单中的项目。 DisplayFor字段不会发布 ,它们只是用于显示。 为了将这些值发回,你需要为你要发布的每个字段使用一个HiddenFor ,以便模型绑定能够发挥它的魔力。