ajax MVC 将部分视图返回为 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4730777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC Return Partial View as JSON
提问by Marty Trenouth
Is there a way to return an HTML string from rendering a partial as part of a JSON response from MVC?
有没有办法从呈现部分返回 HTML 字符串作为来自 MVC 的 JSON 响应的一部分?
public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
if (ModelState.IsValid)
{
if(Request.IsAjaxRequest()
return PartialView("NotEvil", model);
return View(model)
}
if(Request.IsAjaxRequest())
{
return Json(new { error=true, message = PartialView("Evil",model)});
}
return View(model);
}
回答by cacois
You can extract the html string from the PartialViewResult object, similar to the answer to this thread:
您可以从 PartialViewResult 对象中提取 html 字符串,类似于此线程的答案:
PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.
PartialViewResult 和 ViewResult 都从 ViewResultBase 派生,因此相同的方法应该适用于两者。
Using the code from the thread above, you would be able to use:
使用上面线程中的代码,您将能够使用:
public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
if (ModelState.IsValid)
{
if(Request.IsAjaxRequest())
return PartialView("NotEvil", model);
return View(model)
}
if(Request.IsAjaxRequest())
{
return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
}
return View(model);
}
回答by Manatherin
Instead of RenderViewToStringI prefer a approach like
而不是RenderViewToString我更喜欢这样的方法
return Json(new { Url = Url.Action("Evil", model) });
then you can catch the result in your javascript and do something like
然后你可以在你的javascript中捕获结果并执行类似的操作
success: function(data) {
$.post(data.Url, function(partial) {
$('#IdOfDivToUpdate').html(partial);
});
}
回答by Ricardo Cardoso
Url.Action("Evil", model)
Url.Action("Evil", 模型)
will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51
将生成一个 get 查询字符串,但您的 ajax 方法是 post 并且它会抛出 500(内部服务器错误)的错误状态。– Fereydoon Barikzehy 2 月 14 日 9:51
Just Add "JsonRequestBehavior.AllowGet" on your Json object.
只需在您的 Json 对象上添加“JsonRequestBehavior.AllowGet”。

