MVC Return Partial View as JSON

2019-01-02 16:58发布

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

3条回答
君临天下
2楼-- · 2019-01-02 17:31

Instead of RenderViewToString I prefer a approach like

return Json(new { Url = Url.Action("Evil", model) });

then you can catch the result in your javascript and do something like

success: function(data) {
    $.post(data.Url, function(partial) { 
        $('#IdOfDivToUpdate').html(partial);
    });
}
查看更多
零度萤火
3楼-- · 2019-01-02 17:32

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

Render a view as a string

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);
}
查看更多
回忆,回不去的记忆
4楼-- · 2019-01-02 17:49

Url.Action("Evil", model)

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

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

查看更多
登录 后发表回答