第二章 下山遇虎(@helper)

@helper方法定义

 使用@helper关键字可以定义一个方法,这样就可以在页面中调 用这个方法了,和C#中的方法一样。在页面中定义的方法可以访问ViewBag,HttpContext等等页面的属性,返回的类型为 “HelperResult”。其他的写法和普通的方法没有区别,主要用于列表等等需要重复写进行可重复调用。

1.创建MVC4项目,选择模版-Internet应用程序

修改HomeController中的About()

  public ActionResult About()
        {
            ViewBag.Message = "你的应用程序说明页。";
            LoginModel login = new LoginModel();
            login.Password = "1234";
            return View(login);
        }

About.cshtml页面

 @helper Truncate(string input, int length)
     {
     if (input.Length <= length)
     {
        @input
     }
     else
     {
        @input.Substring(0, length)<text>...</text>
     }
}

@Html.TextBoxFor(t => t.Password)
@Truncate(Model.Password,3)

结果:

 

 

 

posted @ 2013-09-26 18:21  心存善念  阅读(1375)  评论(0编辑  收藏  举报