• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

asp.net模板引擎Razor调用外部方法用法实例

asp 搞代码 4年前 (2022-01-03) 38次浏览 已收录 0个评论

这篇文章主要介绍了asp.net模板引擎Razor调用外部方法用法,实例分析了Razor调用外部方法的相关使用技巧,需要的朋友可以参考下

本文实例讲述了asp.net模板引擎Razor调用外部方法用法。分享给大家供大家参考。具体如下:

首先使用Razor的步骤:读取cshtml、解析cshtml同时指定cacheName。

而这个步骤是重复的,为了遵循DRY原则,将这段代码封装为一个RazorHelper()方法

 public class RazorHelper { public static string ParseRazor(HttpContext context, string csHtmlVirtualPath, object model) { string fullPath = context.Server.MapPath(csHtmlVirtualPath); string cshtml = File.ReadAllText(fullPath); string cacheName = fullPath + File.GetLastWriteTime(fullPath); string html = Razor.Parse(cshtml,model,cacheName); return html; } } 

如何在cshtml中用Razor调用外部方法

1. 首先在cshtml文件引用test1和test2所在类的命名空间

 @using WebTest1.RazorDemo;<!--test1和test2所在类的命名空间-->  <title></title> @RazorTest.test1()<br /> @RazorTest.test2() 

2. 在一般处理程序中调用RazorHelper.ParseRazor(),将读取到的cshtml文件返回给客户

 public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string html = RazorHelper.ParseRazor(context, @"~/Razordemo/Razor2.cshtml", null); context.Response.Write(html); } 

为什么要在cshtml文件中调用方法呢?

先看一个繁琐的,在cshtml中插入checkbox的处理

1. 一般处理程序

 bool gender = true; string html = RazorHelper.ParseRazor(context, @"~/Razordemo/Razor2.cshtml", new { Gender = gender }); 

2. cshtml文件中处理checkbox的checked状态

是不是很乱?处女座不能忍。

我们知道方法可以封装一些重复代码,调用方法让cshtml页面更简洁。

举个例子:

要在cshtml页面插入一个checkbox。

1. 首先封装一个CheckBox()方法

 public static RawString CheckBox(string name, string id, bool isChecked) { StringBuilder sb = new StringBuilder(); sb.Append(""); return new RawString(sb.ToString()); } 

2. 在一般处理程序中读取和解析cshtml文件

 string html = RazorHelper.ParseRazor(context, @"~/Razordemo/Razor2.<i style="color:transparent">来源gaodai$ma#com搞$$代**码网</i>cshtml", null); context.Response.Write(html); 

3. 在cshtml文件中调用CheckBox()方法,将checkbox插入cshtml

 @using WebTest1.RazorDemo;<!--test1和test2所在类的命名空间-->  <title></title> @RazorTest.CheckBox("apple","apple",true) 

希望本文所述对大家的asp.net程序设计有所帮助。

以上就是asp.net模板引擎Razor调用外部方法用法实例的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:asp.net模板引擎Razor调用外部方法用法实例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址