我试图在这里关注一些good posts以使其工作,但每次我点击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" }))
{
<div style="float:right; width:500px">
<div id="message"></div>
<input id="btnSubmit" type="submit" value="Select Vendor" />
</div>
此处缩写的视图非常长(仅显示要查看的模型值)。
<div id="viewform">
<div id="viewform-contact" style="float:left;">
<fieldset>
<legend>Contact Information</legend>
@Html.HiddenFor(model => model.ProfileID)
<div class="view-field">
@Html.LabelFor(model => model.Name)
@Html.DisplayFor(model => model.Name)
</div>
<br />
<div class="view-field">
@Html.LabelFor(model => model.Email)
@Html.DisplayFor(model => model.Email)
</div>
<br />
<div class="view-field">
@Html.LabelFor(model => model.Phone)
@Html.DisplayFor(model => model.Phone)
</div>
<br />
<div class="view-field">
@Html.LabelFor(model => model.Website)
@Html.DisplayFor(model => model.Website)
</div>
<br />
<div class="view-field">
@Html.LabelFor(model => model.CompanyName)
@Html.DisplayFor(model => model.CompanyName)
</div>
<br />
<div class="view-field">
@Html.LabelFor(model => model.Address1)
@Html.DisplayFor(model => model.Address1)
</div>
<br />
<div class="view-field">
@Html.LabelFor(model => model.Address2)
@Html.DisplayFor(model => model.Address2)
</div>
<br />
<div class="view-field">
@Html.LabelFor(model => model.City)
@Html.DisplayFor(model => model.City)
</div>
<br />
<div class="view-field">
@Html.LabelFor(model => model.State)
@Html.DisplayFor(model => model.State)
</div>
<br />
<div class="view-field">
@Html.LabelFor(model => model.Zip)
@Html.DisplayFor(model => model.Zip)
</div>
<br />
<div class="view-fieldwide">
@Html.LabelFor(model => model.VendorNotes)
</div>
<br />
<div class="view-fieldwide">
@Html.DisplayFor(model => model.VendorNotes)
</div>
<br /><br />
</fieldset>
</div>
}
控制器。我已经用一两种形式尝试了上述内容。使用上面的代码,模型包含除了隐藏在输入字段中的ProfileID之外的所有空值。我认为传递模型应该工作而不必为每个模型值创建一个隐藏字段?
[HttpPost]
public ActionResult SelectVendor(VendorProfile pageModel)
{
// handle selected vendor
_DAL.SelectVendor(pageModel.ProfileID);
return Content("This Vendor has been selected", "text/html");
}
ANSWER
由于使用DisplayFor
,模型值未绑定答案 0 :(得分:7)
正如评论中所述,您实际上希望使用DisplayFor
查看模型中放置在表单中的项目。 DisplayFor
字段不会发布,它们只是用于显示。为了发回这些值,您需要为要发布的每个字段HiddenFor
,以便模型绑定能够发挥作用。