Rendering Partial View from Inside a Controller Action in C#:
Sometimes I find a need to a rendered HTML string from inside an action (a response to AJAX call for example).The RenderPartialView function below assumes it's a member method of a class derived from the System.Web.Mvc.Controller class.
Function description: Renders the partial view and returns the generated Html. I think it's easier than returning the raw data and having jQuery generates the HTML. Params: partialViewFullPath - The path and extension to the partial view. for example, ~/Views/Controller/ViewName.cshtml model - Almost always we expect a model Returns: HTML string generated by the the MVC framework itself.
public string RenderPartialView(string partialViewFullPath, object model){
/* to avoid null ref exception when unit testing */
if (HttpContext == null || HttpContext.Request == null)
{
return string.Empty;
}
if (string.IsNullOrEmpty(partialViewFullPath))
{
throw new ArgumentException("partialViewName");
}
ViewDataDictionary viewData = new ViewDataDictionary(model);
var razorView = new RazorView(this.ControllerContext, partialViewFullPath
, null, false, new string[] { "cshtml" });
var sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (HtmlTextWriter tw = new HtmlTextWriter(sw))
{
ViewContext viewContext = new ViewContext(this.ControllerContext
,razorView,viewData, this.TempData, tw);
razorView.Render(viewContext, tw);
}
}
return sb.ToString();
}
The RenderPartialView function can be called as the following example code shows
[HttpPost]
public ActionResult SomeAction(int id)
{
///...
var result = new AjaxReturnObjectModel();
result.Success = true;
result.Html = RenderPartialView("~/Views/Controller/PartialView.cshtml", model);
return Json(result, JsonRequestBehavior.DenyGet);
}
Hope this helps.
No comments:
Post a Comment