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>
 
項目結構:
運行結果:
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM