Using the Razor view engine to render views as strings in ASP.

Source: Internet
Author: User
Tags httpcontext

First, preface

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.

This article uses the native method of the ASP . I also implemented this view engine in YOYOFX (https://github.com/maxzhang1985/YOYOFx/ Blob/master/aspnetcore/yoyo. AspNetCore.ViewEngine.Razor).

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 in. NET core razorengine Open source components are not ported, so let's do it on our own.

Second, implement the view renderer

In fact, in ASP. NET Core MVC provides us with such a method, but it is not very convenient to use, we have to package it.

The framework has already provided us with a view rendering interface irazorviewengine through its findview method to find the view and the. cshtml file, and of course the lookup method corresponds to the view path rule in MVC, which is a thing:)

Let's take a step-by-step implementation, first we create a view renderer interface:

 Public Interface iviewrenderservice{    Task<string> Rendertostringasync (stringobject model);}

Then the implementation of the class, the code is very simple to see understand:

 Public classviewrenderservice:iviewrenderservice{Private ReadOnlyIrazorviewengine _razorviewengine; Private ReadOnlyItempdataprovider _tempdataprovider; Private ReadOnlyIServiceProvider _serviceprovider;  PublicViewrenderservice (irazorviewengine razorviewengine, Itempdataprovider Tempdataprovider, IServi Ceprovider 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 (); }        }}
third, how to use

We use a simple example to illustrate how to use the renderer above.

1, establish ViewModel  
 Public class myuserviewmodel{     publicstringsetget;}}
2. Build a View
@model webapplication6.models.myuserviewmodel@{    null;} <! DOCTYPE html>string</title>      @Model. Name</div></body>
3, modify the HomeController
 Public classhomecontroller:controller{PrivateIviewrenderservice _viewrenderservice;  PublicHomeController (Iviewrenderservice viewsenderenderservice) {_viewrenderservice=Viewsenderenderservice; }         Public AsyncTask<iactionresult>Index () {varuser =NewMyuserviewmodel {Name ="Hello World" }; varresult =await_viewrenderservice.rendertostringasync ("home/template1", user); returnContent (Result); }}
4, don't forget the startup
 Public void configureservices (iservicecollection services) {      services. addscoped<iviewrenderservice, viewrenderservice>();      Services. Addmvc ();}
four, written in the last

Finally, I can only say that in the ASP. NET core is all things di ah, in fact, the implementation of ASP.

GITHUB:HTTPS://GITHUB.COM/MAXZHANG1985/YOYOFX If you feel you can also invite the Star , Welcome to communicate together.

. NET Core Open Source Learning Group: 214741894

Using the Razor view engine to render a view as a string 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.