提问人:mike 提问时间:10/6/2012 最后编辑:divibisanmike 更新时间:8/31/2018 访问量:4865
jQuery.Ajax 与 Ajax.beginform 与不显眼的 JavaScript
jQuery.Ajax vs Ajax.beginform with unobtrusive JavaScript
问:
第一篇文章,请温柔:)
我对 MVC3 比较陌生,正在构建一个 Web 应用程序。
我有几个带有复选框的页面,这些复选框可以打开/关闭功能,当它们发生变化时,我通过jQuery Ajax调用提交并向我返回json成功/失败,以便我可以显示一条消息。
我有一些表单,其中包含我刚刚提交的一堆字段(不是使用 Ajax)并检查模型状态是否有效等。如果没有,则重新显示带有消息的表单。我想改用 Ajax 来做到这一点。
我有一个使用 Ajax.BeginForm 的表单,该表单正确提交到控制器,对模型进行验证,如果有错误,我将返回一个部分视图,该视图使用 UpdateTargetId 替换。
我想做的是这个......如果模型有效且保存成功,我仍然需要返回部分视图,因为无论如何 UpdateTargetId 都会替换我的表单。我想发回某种“成功”标志,这样我就可以显示一条消息,说“您的数据已保存”或其他内容。
如果 Ajax 调用成功,则触发 OnSuccess,并且不关心模型是否有效。
我可以使用jQuery.Ajax提交表单,并在控制器中返回返回PartialView以及成功或失败?
谁能说出构建“Ajax”Web 应用程序时的最佳实践是什么?
答:
您可以使用纯 javascript 而不是使用 helper 方法来处理此问题。Ajax.Beginform
@model ProductViewModel
<div id="divForm">
@using(Html.Beginform())
{
@Html.TextBoxFor(x=>x.Name)
@Html.TextBoxFor(x=>x.Location)
<input type="submit" id="btnSave" />
}
</div>
<div id="divItem" />
<script type="text/javascript">
$(function(){
$("#btnSave").click(function(e){
e.preventDefault(); // prevent the default form submit
var form=$(this).closest("form");
$.post(form.attr("action"),form.serialize(),function(result){
if(result.Status=="success")
{
//show message and load the new partial view if needed.
$(#divForm").hide();
$("#divItem").html(reuslt.ViewHTML);
}
else
{
alert("Error");
}
});
});
});
</script>
假设您有一个 HttpPost 操作方法,该方法接受我们的表单 subimt 并返回 JSON 数据。
[HttpPost]
public ActionResult Edit(ProductViewModel model)
{
// here you may validate the model and save if needed and return JSON back.
//to do : return JSON
}
响应 JSON 应采用以下格式。
{ "Status" : "success", "ViewHTML" : "<p>This is some markup</p>" }
此答案解释了如何在 JSON 响应中返回 ViewResult。
评论
下一个:关闭不显眼的验证运行时?
评论