新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

如何在asp.net中使用Razor调用外部方法-创新互联

今天就跟大家聊聊有关如何在asp.net中使用Razor调用外部方法,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

成都创新互联公司主营满洲网站建设的网络公司,主营网站建设方案,App定制开发,满洲h5小程序设计搭建,满洲网站营销推广欢迎满洲等地区企业咨询

首先使用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;




 


 @RazorTest.test1()
 @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.cshtml", null);
context.Response.Write(html);

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

@using WebTest1.RazorDemo;




 


 @RazorTest.CheckBox("apple","apple",true)

看完上述内容,你们对如何在asp.net中使用Razor调用外部方法有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。


网页题目:如何在asp.net中使用Razor调用外部方法-创新互联
链接URL:http://www.wjwzjz.com/article/hophh.html
在线咨询
服务热线
服务热线:028-86922220
TOP