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