public ActionResult MyActionMethod(MyModel model)
{
//some code
string myVar= ActionMethod2(model).toString();
//use myVar
Method3(myVar, otherVar);
}
public ActionResult ActionMethod2()(MyModel model)
{
return View(model);
}
private Method3(string myVar, int otherVar)
{
//do something;
}
As sample code, above, I have a method that returns .cshtml
view, called ActionMethod2
.
I want to use the returned html as a string variable in my action method.How is that possible?
First Mistake is ActionMethod2
return View, And you can get it directly from MyActionMethod
protected string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
public ActionResult MyActionMethod(MyModel model)
{
//some code
//string myVar= ActionMethod2(model).toString();
var myVar = RenderPartialViewToString("yourviewName", model);
//use myVar
Method3(myVar, otherVar);
}
try this and it will work with you.