Using the Razor view engine to render a view as a string (go) in ASP.

Source: Internet
Author: User
Tags httpcontext

First, the View rendering description

In some project requirements may need to produce static pages according to the template, then you can use the Razor syntax to directly parse your page to generate a static page of the parsed page, so many scenarios, not limited to generating static pages, The view engine gives us the ability to generate code or text from the model to the view.

Of course, in the era of MVC 4 and 5, we also used a third-party view engine such as Razorengine , when the razor in MVC was more tightly coupled to the framework, Third-party open source components enable us to use razor render views as text in any project, but razorengine open source components in. NET core are not ported.

Second, this example creates a service that handles the view and parameters that will make the path, parsing it into a string

/// <summary>///Defining the View rendering service/// </summary> Public classviewrenderservice:iviewrenderservice{Private ReadOnlyIrazorviewengine _razorviewengine; Private ReadOnlyItempdataprovider _tempdataprovider; Private ReadOnlyIServiceProvider _serviceprovider;  PublicViewrenderservice (irazorviewengine razorviewengine, Itempdataprovider Tempdataprovider, IServiceProvide R serviceprovider) {_razorviewengine=Razorviewengine; _tempdataprovider=Tempdataprovider; _serviceprovider=serviceprovider; }     Public Asynctask<string> Rendertostringasync (stringViewName,Objectmodel) {        varHttpContext =NewDefaulthttpcontext {requestservices =_serviceprovider}; varActioncontext =NewActioncontext (HttpContext,NewRoutedata (),Newactiondescriptor ()); using(varSW =NewStringWriter ()) {            varViewResult = _razorviewengine.findview (Actioncontext, ViewName,false); if(Viewresult.view = =NULL)            {                Throw NewArgumentNullException ($"{viewName} does not match any available view"); }            varViewdictionary =NewViewdatadictionary (NewEmptymodelmetadataprovider (),Newmodelstatedictionary ()) {Model=model}; varViewContext =NewViewContext (Actioncontext, Viewresult.view, Viewdictionary, Newtempdatadictionary (Actioncontext.httpcontext, _tempdataprovider), SW,Newhtmlhelperoptions ()); awaitViewResult.View.RenderAsync (ViewContext); returnSW.        ToString (); }    }} Public Interfaceiviewrenderservice{Task<string> Rendertostringasync (stringViewName,Objectmodel);}

Use procedure:

1. Registration service, in Configureservices ()

// bind service, Services. Addscoped<iviewrenderservice, viewrenderservice> ();

2. Invoking the method through the service in the controller

 Public classemall1mvccontroller:controller{PrivateIviewrenderservice _view =NULL;  PublicEmall1mvccontroller (Iviewrenderservice view) { This. _view=view; }     PublicIactionresult Index () {returnView (123); }    //Call the service method, return the HTML string     Public Asynctask<string>Test1 () {return await_view. Rendertostringasync ("Emall1mvc/index",456); }}
@model int@{    viewdata["Title"] = "Index";} < H2 > Index</h2> Test variables are as follows:<p>     @Model   </ P >

return the result;

More:

ASP. NET Core custom set HTTP cache processing

ASP. NET Core-middleware (middleware) uses

ASP. NET Core prevents instances of picture hotlinking with custom middleware (GO)

Use the Razor view engine to render a view as a string (go) in an ASP. NET Core

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.