mvc中使用JQuery异步提交表单
js代码:
<script type="text/javascript">
function submitForm() {
$.ajax({
type: 'POST',
url: '@Url.Action("AJAXReview", "Common")',
data: $("#form1").serialize(),
success: function (data) {
if (data.res)
alert("提交成功");
else
alert("提交失败,失败信息为:" + data.info);
}
})
}
</script>
view代码:
@using (Html.BeginForm("Review", "Common", FormMethod.Post, new
{
id = "form1"
}))
{
<fieldset>
<legend>评论 </legend>
<ul>@Html.ValidationSummary(true)
@Html.HiddenFor(i => i.ObjID)
@Html.HiddenFor(i => i.ObjType)
<li></li>
<li>标题:@Html.TextBoxFor(i => i.Title)</li>
<li>@Html.ValidationMessageFor(i => i.Title)</li>
<li>内容:@Html.TextAreaFor(i => i.Content)</li>
<li>@Html.ValidationMessageFor(i => i.Content)</li>
</ul>
</fieldset>
<input type="button" onclick="submitForm()" value="提交" />
}
Controller代码:
[HttpPost]
public JsonResult AJAXReview(Review entity)
{
JsonResult js = new JsonResult();
js.Data = new { res = true };
if (ModelState.IsValid)
{
//相关逻辑
}
else
{
js.Data = new { res = false, info = "请认真填写表单!" };
}
return js;
}