MVC返回部分查看JSON [英] MVC Return Partial View as JSON
本文介绍了MVC返回部分查看JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法从渲染部分作为从MVC JSON响应的一部分返回一个HTML字符串?
公众的ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel模型)
{
如果(ModelState.IsValid)
{
如果(Request.IsAjaxRequest()
返回PartialView(NotEvil,模型);
返回查看(模型)
}
如果(Request.IsAjaxRequest())
{
返回JSON(新{错误= TRUE,消息= PartialView(邪恶的,模型)});
}
返回查看(模型);
}
解决方案
您可以从中提取PartialViewResult对象中的HTML字符串,类似于回答这个主题:
PartialViewResult和的ViewResult从ViewResultBase两个派生,所以同样的方法应该双管齐下。
使用从上面的线程code,你就可以使用:
公众的ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel模型)
{
如果(ModelState.IsValid)
{
如果(Request.IsAjaxRequest())
返回PartialView(NotEvil,模型);
返回查看(模型)
}
如果(Request.IsAjaxRequest())
{
返回JSON(新{错误= TRUE,消息= RenderViewToString(PartialView(邪恶的,型号))});
}
返回查看(模型);
}
Is there a way to return an HTML string from rendering a partial as part of a JSON response from MVC?
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);
}
解决方案
You can extract the html string from the PartialViewResult object, similar to the answer to this thread:
PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.
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);
}
这篇关于MVC返回部分查看JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文