MVC 将部分视图作为 JSON 返回 [英] MVC Return Partial View as JSON

查看:40
本文介绍了MVC 将部分视图作为 JSON 返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法通过渲染部分作为来自 MVC 的 JSON 响应的一部分来返回 HTML 字符串?

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);
    }

推荐答案

可以从 PartialViewResult 对象中提取 html 字符串,类似于本帖的回答:

You can extract the html string from the PartialViewResult object, similar to the answer to this thread:

将视图渲染为字符串

PartialViewResult 和 ViewResult 都派生自 ViewResultBase,因此相同的方法应该适用于两者.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆