Razor 中的@helper 与 @function 用法

ASP.NET MVC 辅助方法使用
本文介绍ASP.NET MVC中辅助方法(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>
 
项目结构:
运行结果:
 
 

转载于:https://www.cnblogs.com/sjqq/p/8806021.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值