Razor 中的@helper 与 @function 用法

@helper : 可以有返回值,也可以没有返回值
@function :需要有返回值
可以将View中公共部分的代码抽取出来,变成一个独立的方法
 
公共部分 view
       抽出的公共部分的view 必须放在App_Code目录下,文件名 xxx.cshtml . 文件名就是类名称
CommonUI.cshtml
  • 无返回值
@helper ShowCustomerInfo(Customer customer)
{
    <ul>
        <li>@customer.CompanyName</li>
        <li>@customer.CustomerID</li>
    </ul>
          
}
  • 有返回值
@helper mutiply(int a,int b)
{
    var r = a * b;
    @r;
}
 
 
@functions {
 
   public static IHtmlString GetCurrentTime()
   {
       return new HtmlString( DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
   }
}
 
Models 中的代码:
namespace Step1
{
    public class Customer
    {
        public string CustomerID
        {
            get;
            set;
        }
 
        public string CompanyName
        {
            get;
            set;
        }
    }
}
 
Controller 中的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace Step1.Controllers
{
    public class CommonUIController : Controller
    {
        //
        // GET: /CommonUI/
 
        public ActionResult Helper()
        {
            Customer c = new Customer() {
             CompanyName="Redwave",
             CustomerID ="hbb0b0"          
            };
            return View(c);
        }
 
    }
}
 
 
 View 中的代码:
@using Step1.App_Code;
@{
    ViewBag.Title = "Helper";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>Helper</h2>
<div>
    @@helper 无返回值
</div>
<div>
    @ASP.CommonUI.ShowCustomerInfo(Model)
</div>
<div>
    @@helper 有返回值
</div>
<div>
   5*4=  @ASP.CommonUI.Mutiply(5,4).ToString()
</div>
<div>
    @@function
</div>
<div>
    @ASP.CommonUI.GetCurrentTime()
</div>
 
项目结构:
运行结果:
 
 
posted @ 2016-01-05 22:45  b0b0  阅读(2417)  评论(0编辑  收藏  举报