Partial Views vs. Json (or both)

前端 未结 4 1384
长情又很酷
长情又很酷 2020-12-13 07:16

I use ASP.NET MVC with jQuery and have a lot of Ajax requests to my controllers.

Use Partial Views (usercontrols) to build the intial view when a page is loaded. The

4条回答
  •  囚心锁ツ
    2020-12-13 07:40

    Based on this stackoverflow anwser I have just set out to do the same thing.

    First create an extension method for the controller class.

    public static string RenderViewToString(this Controller controller, string viewName, object model)
    {
        using (var writer = new StringWriter())
        {
             var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
             controller.ViewData.Model = model;
             var viewCxt = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer);
             viewCxt.View.Render(viewCxt, writer);
             return writer.ToString();
         }
    }
    

    Then return the json in the controllers action method.

    return Json(new {
      Html = this.RenderViewToString("MyView", model),
        SomeExtraData = data
    });
    

    Your ajax requests will now receive json with the html contained in it. Still experimenting with this approach over returning plain Html fragments.

    Hope that helps.

    EDIT Updated to work with razor

提交回复
热议问题