In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-09-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to use the Razor view engine name. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
First of all, the Razor domain name space used.
UsingSystem.Web.Razor; usingSystem.Web.Razor.Generator; usingSystem.Web.Razor.Parser
The first step, dynamic compilation: parse the view file, generate code, yes, generate code, first. The syntax of Razor can be said to be proprietary, and you need to convert it into standard code before compiling it to generate the familiar C# class Type. It is important to note that the template base class I use in the following code is my own TeamplateBase, which will be given a simple implementation later, with the benefit of flexibility, of course. You can also use Asp.NetMVC 's System.Web.Mvc.WebViewPage directly, but I haven't tried it. There may be other problems that can't be guaranteed.
PublicstaticTypeCompile (stringtemplate_path) {/ / prepare temporary class name, read template file and Razor code generator varclass_name= "c" + Guid.NewGuid (). ToString ("N"); varbase_type=typeof (TemplateBase) .MakeGenericType (typeof (T)); vartemplate=File.ReadAllText (template_path) Varhost=newRazorEngineHost (newCSharpRazorCodeLanguage (), () = > newHtmlMarkupParser ()) {DefaultBaseClass=base_type.FullName, DefaultClassName=class_name, DefaultNamespace= "YourNameSpace.dynamic", GeneratedClassContext= newGeneratedClassContext ("Execute", "Write", "WriteLiteral", "WriteTo", "WriteLiteralTo", "YourNameSpace.TemplateBase")}; host.NamespaceImports.Add ("System"); host.NamespaceImports.Add ("YourNameSpaces") / / generate code CodeCompileUnitcode; using (varreader=newStringReader (template)) {vargeneratedCode=newRazorTemplateEngine (host) .GenerateCode (reader); code=generatedCode.GeneratedCode;} / / prepare compilation parameters var@params=newCompilerParameters {IncludeDebugInformation=false, TempFiles=newTempFileCollection (AppDomain.CurrentDomain .DynamicDirectory), CompilerOptions= "/ target:library/optimize", GenerateInMemory=false} Varassemblies=AppDomain.CurrentDomain .GetAssemblies () .Where (a = >! a.IsDynamic) .Select (a = > a.Location) .ToArray (); @ params.ReferencedAssemblies.AddRange (assemblies); / / compile varprovider=newCSharpCodeProvider (); varcompiled=provider.CompileAssemblyFromDom (@ params,code); if (compiled.Errors.Count > 0) {varcompileErrors=string.Join ("rn", compiled.Errors.Cast () .Select (o = > o.ToString () ThrownewApplicationException ("FailedtocompileRazor:" + compileErrors);} / / after compilation, return the compiled dynamic Type returncompiled.CompiledAssembly.GetType ("Skight.Arch.Presentation.Web.Core .ViewEngins.Razor.dynamic." + class_name);}
How to use the Razor View engine name
The second step is much simpler, just like any static class, create an instance with reflection, then copy the Model object execution template, and the final output is that the data of the Model class is automatically embedded.
PublicstaticstringRender (Tmodel,stringtemplate_path) {vartype=Compile (template_path); / / create view instance varinstance= (TemplateBase) Activator.CreateInstance (type); / / execute template (embed data into file) instance.Model=model; instance.Execute (); / / output final result varresult=instance.Result; returnresult;}
Finally, take a look at the view template class, a base class and a generic base class, the latter for the pre-type Model
PublicabstractclassTemplateBase {publicstringLayout {get;set;} publicUrlHelperUrl {get;set;} publicFuncRenderBody {get;set;} publicstringPath {get;internalset;} publicstringResult {get {returnWriter.ToString ();} protectedTemplateBase () {} publicTextWriterWriter {get {if (writer==null) {writer=newStringWriter ();} returnwriter;} set {writer=value }} privateTextWriterwriter; publicvoidClear () {Writer.Flush ();} publicvirtualvoidExecute () {} publicvoidWrite (object@object) {if (@ object==null) {return;} Writer.Write (@ object);} publicvoidWriteLiteral (string@string) {if (@ string==null) {return;} Writer.Write (@ string) } publicstaticvoidWriteLiteralTo (TextWriterwriter,stringliteral) {if (literal==null) {return;} writer.Write (literal);} publicstaticvoidWriteTo (TextWriterwriter,objectobj) {if (obj==null) {return;} writer.Write (obj);}} publicabstractclassTemplateBase:TemplateBase {publicTModel {get;set }} this is the end of the article on "how to use the engine name of Razor View". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
The market share of Chrome browser on the desktop has exceeded 70%, and users are complaining about
The world's first 2nm mobile chip: Samsung Exynos 2600 is ready for mass production.According to a r
A US federal judge has ruled that Google can keep its Chrome browser, but it will be prohibited from
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
About us Contact us Product review car news thenatureplanet
More Form oMedia: AutoTimes. Bestcoffee. SL News. Jarebook. Coffee Hunters. Sundaily. Modezone. NNB. Coffee. Game News. FrontStreet. GGAMEN
© 2024 shulou.com SLNews company. All rights reserved.