ASP MVC View Content as JSON

2019-01-21 17:44发布

I have a MVC app with quite a few Controller Actions that are called using Ajax (jQuery) and return partial views content which updates a part of the screen. But what I would rather do is return JSON something like this.

return Json(new { 
    Result = true, 
    Message = "Item has been saved", 
    Content = View("Partial") 
});

Where the HTML is just a property of the Json. What this means is I need to retrieve the HTML that is rendered by the View method. Is there any easy way to do this, a few examples I have seen are quite convoluted.

Edit: This question was originally for ASP.NET MVC 1, but if version 2 makes it easier I would like to hear the answer.

9条回答
贪生不怕死
2楼-- · 2019-01-21 18:14

Craig,

Have a look at this. Jeffery Palermo has written a SubController for ASP.NET MVC that should accomplish what you want:

MvcContrib - now with SubController support for ASP.NET MVC: http://jeffreypalermo.com/blog/mvccontrib-now-with-subcontroller-support/

查看更多
唯我独甜
3楼-- · 2019-01-21 18:19

I don not know since which version number you can do this, but nowadays you can return JSON in a very simple way:

public ActionResult JSONaction()
{
    return Json(data, JsonRequestBehavior);
}

no need for elaborate helpers etc.

data is of course your data from your model JsonRequestBehavior specifies whether HTTP GET requests from the client are allowed. (source), is optional DenyGet is default behaviour, so if used mostly JsonRequestBehavior.AllowGet and here is why this is in there

查看更多
够拽才男人
4楼-- · 2019-01-21 18:21

I found a more recent answer using Razor that may be helpful http://codepaste.net/8xkoj2

public static string RenderViewToString(string viewPath, object model,ControllerContext context)
{            
    var viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
    var view = viewEngineResult.View;


    context.Controller.ViewData.Model = model;

    string result = String.Empty;
    using (var sw = new StringWriter())
    {

        var ctx = new ViewContext(context, view, 
                                  context.Controller.ViewData, 
                                  context.Controller.TempData, 
                                  sw);
        view.Render(ctx, sw);

        result = sw.ToString();
    }

    return result;
}
查看更多
登录 后发表回答