MVC obtains the string generated by a view or partialview.

Source: Internet
Author: User

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 ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.