我正在尝试使用ASP.NET MVC 5将部分视图返回到我的页面,并让jQuery用部分视图替换元素。
这是我的控制器,它将处理所有这些请求。
public ActionResult Contact()
{
//Some Unrelated code
ViewBag.Loc = "";
return View();
}
[HttpPost]
public ActionResult Contact(form form)
{
if(ModelState.IsValid)
{
//Some verification code
//Some unrelated code
ViewBag.loc = "";
return PartialView("_ContactThanks");
}
ViewBag.loc = "error";
return View();
}
这是我的表格:
<div id="formSection>
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "contactForm" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.LabelFor(form => form.name)
@Html.EditorFor(form => form.name)
@Html.ValidationMessageFor(form => form.name)
@Html.LabelFor(form => form.email)
@Html.EditorFor(form => form.email)
@Html.ValidationMessageFor(form => form.email)
@Html.LabelFor(form => form.message, new { @class = "label-info" })
@Html.EditorFor(form => form.message)
@Html.ValidationMessageFor(form => form.message)
<input type="submit" value="Send" class="btn btn-sm btn-default" />
}
</div>
这是我的jQuery:
$('#contactForm').submit(function() {
$('#progress').show();
$.post().done(function(response) {
if ("@ViewBag.loc" == "") {
setTimeout(function() { $('#formSection').html(response); }, 1000);
} else {
$('#progress').hide();
$("#errorMessage").show();
}
});
return false;
});
当它返回帖子时,它会将页面空白,然后重新加载实际的局部视图,而不是从局部视图中获取html并将其导入div。
当我使用标准HTML表单时,这部分代码工作正常,但是我无法使用我的模型和控制器内置的数据验证。
有效的HTML表单:
<div id="formSection">
<h3>@ViewBag.TheMessage</h3>
<form method="post" id="contactForm">
<label class="label-info">Name</label>
<textarea class="form-control" rows="1" data-bind="value: name, valueUpdate:'afterkeydown'" name="name" id="name" maxlength="15" spellcheck="false" required></textarea>
<label class="label-info">Email</label>
<textarea class="form-control" rows="1" data-bind="value: emailadd, valueUpdate:'afterkeydown'" name="emailadd" id="emailadd" maxlength="30" spellcheck="false" required></textarea> <label class="label-info">Message</label>
<textarea class="form-control" rows="4" data-bind="value: comment, valueUpdate:'afterkeydown'" name="comment" id="comment" maxlength="300" spellcheck="false" required></textarea>
<input type="submit" value="Send" class="btn btn-sm btn-default" />
</form>
</div>
和相应的jQuery:
$('#contactForm').submit(function () {
$('#progress').show();
$.post('', {
emailadd: $('#emailadd').val(),
name: $('#name').val(),
comment: $('#comment').val()
}).done(function (response) {
if ("@ViewBag.loc" == "") {
setTimeout(function () { $('#formSection').html(response); }, 1000);
} else {
$('#progress').hide();
$("#errorMessage").show();
}
});
return false;
});
感谢任何帮助。谢谢!