当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net模板引擎Razor调用外部方法用法实例

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

捐精qq,蓝美琪跳舞,陈若仪和林志颖图片

本文实例讲述了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所在类的命名空间-->
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
 <title></title>
</head>
<body>
 @razortest.test1()<br />
 @razortest.test2()
</body>
</html>

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状态

<input type="checkbox" @(model.gender?"checked":"") />
<!--加括号改变优先级,否则编译器会将点model后面的表达式当字符串处理-->

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

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

举个例子:

要在cshtml页面插入一个checkbox。

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

public static rawstring checkbox(string name, string id, bool ischecked)
{
 stringbuilder sb = new stringbuilder();
 sb.append("<input type='checkbox' id='").append(id).append("' ").append("name='").append(name).append("' ");
 if (ischecked)
 {
 sb.append("checked");
 }
 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;<!--test1和test2所在类的命名空间-->
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
 <title></title>
</head>
<body>
 @razortest.checkbox("apple","apple",true)
</body>
</html>

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网