如何将JSON结果返回给Ajax.BeginForm
我有这个简单的forms:
@using (Ajax.BeginForm("CreateProductFromAjaxForm","Product" , null, new AjaxOptions() { HttpMethod = "post", OnSuccess = "getresult" }, null)) { @Html.EditorFor(m => m)
}
并且,为了测试,一个简单的控制器:
[HttpPost] public JsonResult CreateProductFromAjaxForm(CreateProductModel model) { if (!ModelState.IsValid) { return new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { result = "error" } }; } //add to database return new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { result = "success"} }; }
我已将这些添加到Web.Config:
这些到我的脚本包:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js", "~/Scripts/jquery.validate.js", "~/Scripts/jquery.validate.unobtrusive.js" ));
单击“提交”按钮后,结果页面显示:
{"result":"success"}
我希望我可以在OnSuccess="getresult"
处理程序中处理结果,但它似乎不起作用。
基本上我使用Ajax.BeginForm
主要用于客户端validation。
你能告诉我什么是错的吗?
更新:我将HttpMethod = "post"
到AjaxOptions。
更新: getresult
,在Ajax.BeginForm
之上定义,如下所示:
var getresult = function (data) { alert(data.result); };
你需要包含jquery.unobtrusive-ajax.js
文件。
JsonResult只是一种ActionResult派生类,它指示此操作将返回JSON而不是视图或其他内容。
例如:
@using (Ajax.BeginForm("CreateProductFromAjaxForm","Product" , null, new AjaxOptions() { OnSuccess = "getresult" }, null))
这将生成一个元素,该元素将在提交给操作时发送AJAX请求。 为此,您需要在页面中包含以下脚本:
现在剩下的就是写这个onSuccess javascript函数并处理服务器返回的JSON结果:
在页面中
new AjaxOptions() { OnSuccess = "getresult", }
在javascript中
function getresult(data){ alert(data.x); }
在c#中
[HttpPost] public ActionResult CreateProductFromAjaxForm(CreateProductModel model) { if (!ModelState.IsValid) { return Json("error", JsonRequestBehavior.AllowGet); } //add to database return Json(model, JsonRequestBehavior.AllowGet); }
尝试指定HTTP方法:
new AjaxOptions() { OnSuccess = "getresult", HttpMethod = "post" }
例:
@using (Ajax.BeginForm("CreateProductFromAjaxForm", "Product" , null, new AjaxOptions() { OnSuccess = "getresult", HttpMethod = "post" }, null)) { .... }
我的项目遇到了同样的问题。 未加载Ajax库是问题所在。 当我检查我的bundleconfig
和我的布局文件时,它确实有include但是我包含ajax库的绝对名称
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include( "~/Scripts/jquery.unobtrusive-ajax.min.js"));
我的朋友让我用外卡代替。 令人惊讶的是bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include("~/Scripts/jquery.unobtrusive-ajax*"));
开始包括ajax库。
现在我的OnSuccess
函数按预期加载,而不是查看带有json响应的空白屏幕。
代替:
var getresult = function (data) { alert(data.result); };
尝试
function getresult(data) { alert(data.result); };