Returning a rendered HTML partial in a JSON Property in ASP.NET MVC -
I am gladly return JasonSasselt objects or partial ASP.NET views to my controllers in ASP.NET.
I want to return a provided partial view as a property in a JSON object. For example
request
/ post / description / 1
will return
{"Post ID": 1, "HTML": "& lt; p & gt; some markups that have been partially injected & lt; / p & gt;"}
< P> This will allow me to know when postId is handling replies in javascript. Any suggestions on the best way to do this?
Here's some code that is necessary for me to do the work today.
Public Stabilized String RenderPartialToString (String ControlName, Object ViewData) {var viewContext = New ViewContext (); Var urlHelper = New UrlHelper (viewContext.RequestContext); Var viewDataDictionary = New ViewDataDictionary (ViewData); Var viewPage = New ViewPage {ViewData = viewDataDictionary, ViewContext = viewContext, Url = urlHelper}; Var control = viewPage.LoadControl (controlName); ViewPage.Controls.Add (Control); Var sb = new stringbilder (); (Using var tw = new HtmlTextWriter (sw)) (using var sw = new string water (sb)) {viewPage.RenderControl (tw); } Return sb.ToString (); }
You can use it to do RJS style JSON results
Public Virtual ActionResult Index () {var jsonResult = new JsonResult {data = New {Main_content = RenderPartialToString ("~ / visible / contact / MyPartial.ascx", new object ()), secondary_ content = RenderPartialToString ("~ / view / contact / MyPartial.ascx", new SomeObject ()),}}; Jason Returns (Jason Ersalt, Jesenfesti Bihari. Elovaget); }
and partially a strongly watched model
& lt;% @ Control language = "C #" Inherits = "System.Web .mvc ViewUserControl & LT; SomeObject & gt; "& Gt%; & Lt; H1 & gt; My partial & lt; / H1>
Comments
Post a Comment