Skip to content

Instantly share code, notes, and snippets.

@cassioeskelsen
Created February 17, 2011 11:50
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save cassioeskelsen/831567 to your computer and use it in GitHub Desktop.
Save cassioeskelsen/831567 to your computer and use it in GitHub Desktop.
Render a Asp.Net MVC View (Razor) to string
/*
* Original Sample: http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/
*/
public class HomeController : Controller
{
public ActionResult Index()
{
string MyModelData = "";
var teste = RenderPartialViewToString("About", MyModelData);
return View();
}
public ActionResult About()
{
return View();
}
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}
@ChethanRudrappa
Copy link

i am using the above given code, it works fine, but one of my model property value is of decimal type. the value is coming upto here correctly, but once the .ToString() method is called, its truncating and rounding the decimal to nearest values. Any suggestions?

@vmeln
Copy link

vmeln commented Dec 23, 2014

It's behavior of ToString in Decimal. Specify format explicitly in ToString method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment