In development, you sometimes need to obtain the string generated by a view or partialview in the background. As long as you are familiar with ASP. net mvc, you can understand and break out the followingCode. There is nothing advanced. Go directly to the Code:
1. Output view HTML string:
/// <Summary>
/// Description: outputs the view HTML string.
/// </Summary>
/// <Param name = "controller"> </param>
/// <Param name = "viewname"> View File name </param>
/// <Param name = "mastername"> motherboard page file name </param>
/// <Returns> </returns>
Protected static string renderviewtostring (controller, string viewname, string mastername)
{
Iview view = viewengines. Engines. findview (controller. controllercontext, viewname, mastername). view;
Using (stringwriter writer = new stringwriter ())
{
Viewcontext = new viewcontext (controller. controllercontext, view, controller. viewdata, controller. tempdata, writer );
Viewcontext. View. Render (viewcontext, writer );
Return writer. tostring ();
}
}
2. Output The partialview HTML string:
/// <Summary>
/// Description: output the partialview HTML string
/// </Summary>
/// <Param name = "controller"> </param>
/// <Param name = "partialviewname"> Partial View File Names </param>
/// <Returns> </returns>
Protected static string renderpartialviewtostring (Controller controller, string partialviewname)
{
Iview view = viewengines. Engines. findpartialview (controller. controllercontext, partialviewname). view;
Using (stringwriter writer = new stringwriter ())
{
Viewcontext = new viewcontext (controller. controllercontext, view, controller. viewdata, controller. tempdata, writer );
Viewcontext. View. Render (viewcontext, writer );
Return writer. tostring ();
}
}