码迷,mamicode.com
首页 > 其他好文 > 详细

Razor调用外部方法

时间:2015-06-07 20:07:33      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

使用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,在一般处理程序中

string html = RazorHelper.ParseRazor(context, @"~/Razordemo/Razor2.cshtml", null);
context.Response.Write(html);

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

@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>

 

Razor调用外部方法

标签:

原文地址:http://www.cnblogs.com/sean100/p/4558880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!