Quantcast
Viewing all articles
Browse latest Browse all 11

In MVC controller returns rendered html

In MVC development sometime developers need to get rendered html code from controller’s action method. In my one of the requirement I am updating page’s specific portion by java script by json method, so I am updating returned html in related tag by jquery.

Below are the code and description of the solution.

In Below action method is about for refresh page’s section and return new updated HTML.

public JsonResult RefreshPage(string SectionID)
{
   JsonResult result = new JsonResult();
   // My bussiness logic to get data
   string StrReturn = RenderViewToString("HomePage", oTS.Data, this.ControllerContext);
   result.Data = StrReturn.ToString();
   result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
   return result;
}

In this method We have used RenderViewToString method to get rendered html, here “HomePage” is my partial view for this which is actual bind oTS.Data data and generate html.

Below is the method for RenderViewToString

public string RenderViewToString(string viewPath, object model, ControllerContext context)
{
       var viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
       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;
}

So in this way we can return html. and that html will be used by below jquery method by json.

 function RefreshPage() {
        var hiddenID = $('#hdTDetailsID').val();
        var url = '@Url.Content("~/page/RefreshPage")';
        $.ajaxSetup
        (
            {
                cache: false
            }
        );
        $.getJSON(url,
         {
             Sel_TDetailID: hiddenID
         },
        function (data) {
            $(divname).html(data);
        });
    }

In this way we can refresh page’s any of the portion’s data by jquery in MVC. There are other various ways to do it but when you append some data in current data then this approach is useful.

Feel free to write me in case of any question or need more details on this.

Thanks,
Amit Patel
“Enjoy Programming”


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 11

Trending Articles