我正在尝试通过jquery ajax发送和验证表单。 我想知道是否可能以及如何实现这一目标。
我有什么?
查看:
@using (Html.BeginForm("Index", "Home"))
{
<section id="result">
@Html.ValidationSummary(false)
</section>
<section>
@Html.LabelFor(model => model.Isbn)
@Html.TextBoxFor(model => model.Isbn)
@Html.ValidationMessageFor(model => model.Isbn)
</section>
<section>
@Html.LabelFor(model => model.BookNumber)
@Html.TextBoxFor(model => model.BookNumber)
@Html.ValidationMessageFor(model => model.BookNumber)
</section>
<section>
@Html.LabelFor(model => model.Title)
@Html.TextBoxFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</section>
<section>
@Html.LabelFor(model => model.ReleaseDate)
@Html.TextBoxFor(model => model.ReleaseDate)
@Html.ValidationMessageFor(model => model.ReleaseDate)
</section>
<button type="submit">Go</button>
}
我的javascript:
<script>
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize()
})
.success(function (result) {
$('#result').html(result);
})
.error(function () {
alert("oops! some critical stuff");
});
}
return false;
});
});
</script>
最后,我的控制器:
[HttpPost]
public ActionResult Index(Book model)
{
if (!ModelState.IsValid)
return View(model);
if (model.Title.IsEmpty())
{
ModelState.AddModelError("Title", "What are you doing?? The title can't be emtpy!");
return View(model);
}
return View();
}
所以,这只是一个案例研究。 我想让DataAnnotations在客户端工作,这已经是。当我将表单发布到服务器时,通过ModelState.IsValid和ModelState.AddModelError执行更多验证,并将其显示回客户端。
有可能实现这个目标吗?
答案 0 :(得分:1)
想想你在做什么:
要解决此问题 - 请使用局部视图。
即。创建一个新的部分_FormPartial.chstml并将表单内容放入其中。
@Html.ValidationSummary(false)
<section>
@Html.LabelFor(model => model.Isbn)
@Html.TextBoxFor(model => model.Isbn)
@Html.ValidationMessageFor(model => model.Isbn)
</section>
<section>
@Html.LabelFor(model => model.BookNumber)
@Html.TextBoxFor(model => model.BookNumber)
@Html.ValidationMessageFor(model => model.BookNumber)
</section>
<section>
@Html.LabelFor(model => model.Title)
@Html.TextBoxFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</section>
<section>
@Html.LabelFor(model => model.ReleaseDate)
@Html.TextBoxFor(model => model.ReleaseDate)
@Html.ValidationMessageFor(model => model.ReleaseDate)
</section>
<button type="submit">Go</button>
然后更改您的视图以使用此部分视图:
@using (Html.BeginForm("Index", "Home"))
{
<section id="result">
@Html.Partial("_FormPartial")
</section>
}
最后,更新控制器的返回类型以使用PartialView而不是View。
[HttpPost]
public ActionResult Index(Book model)
{
if (!ModelState.IsValid)
return PartialView("_FormPartial", model);
if (model.Title.IsEmpty())
{
ModelState.AddModelError("Title", "What are you doing?? The title can't be emtpy!");
return PartialView("_FormPartial", model);
}
return View();
}
或者,看看使用Ajax.BeginForm为您做繁重的工作。