本篇文章我们来讨论ASP.NET MVC框架中的Helper Method。就是经常用到的类似@Html.TextBox("userName")
的表达式。本篇主要包含两个内容,1.创建自己定义的Helper Method,2.使用MVC框架内置的Helper Method。
Helper Method可以用来封装少量的HTML代码,用更简单的方式来输出常用的内容,就像@Html.TextBox("userName")
这样,是最轻量级的前端代码重用。如果要重用的代码比较复杂,则不建议使用Helper Method来封装,而是采用Partial View 和Child Action来实现。
创建自己定义的Helper Method
创建页面内的Helper Method
举个例子,我们项目中的HomeController类中有一个名叫HelperMethodTest的Action方法,以及对应的View,下面是Action方法的代码
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult HelperMethodTest()
{
ViewBag.Fruits = new string[] { "Apple", "Orange", "Pear" };
ViewBag.Cities = new string[] { "New York", "London", "Paris" };
return View();
}
}
}
下面是View的代码
@{
ViewBag.Title = "HelperMethodTest";
}
<h2>HelperMethodTest</h2>
<div>
Here are the fruits:
<ul>
@foreach (string str in (string[])ViewBag.Fruits)
{
<li>@str </li>
}
</ul>
</div>
<div>
Here are the cities:
<ul>
@foreach (string str in (string[])ViewBag.Cities)
{
<li>@str </li>
}
</ul>
</div>
很明显,在View中存在两个具有相同逻辑的foreach语句段,我们可以通过Helper Method来封装一下,下面是修改后的代码
@{
ViewBag.Title = "HelperMethodTest2";
}
<h2>HelperMethodTest2</h2>
@helper DisplayList(string[] items)
{
<ul>
@foreach (var item in items)
{
<li>@item</li>
}
</ul>
}
<div>
Here are the fruits:
@DisplayList(ViewBag.Fruits)
</div>
<div>
Here are the cities:
@DisplayList(ViewBag.Cities)
</div>
是不是感觉写代码的逼格瞬间得到了提升?@helper DisplayList(string[] items)
定义了一个Helper Method,像一个普通方法一样,但是没有返回值类型,我们在方法体中直接输出HTML标签就行了。@DisplayList(ViewBag.Cities)
用来调用。
创建外部的Helper Method
使用上面这种方式定义的Helper Method,只能在该View页面内调用,如果希望编写一个更加通用的Helper Method,在所有的地方都能够调用的话,也是可以做到的,但是写起来感觉有些许的蹩脚。
首先,我们右键点击Models文件夹,新建一个类,命名为”CustomHelperMethod“,把该类定义为静态的,然后分别引入命名空间System.Web
和System.Web.Mvc
,下面是完整的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication1.Models
{
public static class CustomHelperMethod
{
public static MvcHtmlString DisplayList(this HtmlHelper html, string[] list)
{
TagBuilder tag = new TagBuilder("ul");
foreach (string str in list)
{
TagBuilder itemTag = new TagBuilder("li");
itemTag.SetInnerText(str);
tag.InnerHtml += itemTag.ToString();
}
return new MvcHtmlString(tag.ToString());
}
}
}
定义好了方法以后,在View中使用
@{
ViewBag.Title = "HelperMethodTest3";
}
@using MvcApplication1.Models
<h2>HelperMethodTest3</h2>
<div>
Here are the fruits:
@Html.DisplayList((string[])ViewBag.Fruits)
</div>
<div>
Here are the cities:
@Html.DisplayList((string[])ViewBag.Cities)
</div>
注意,@Html.DisplayList
方法调用时,参数需要进行强制类型转换,否则编译不过,不知道为什么。
Helper Method中的编码问题
最后一行代码return new MvcHtmlString(tag.ToString());
,之所以通过这样的方式返回,是因为MVC框架默认会把发回到页面上的数据自动编码,但如果我们真的想返回代用’<’或’>’的代码时,可以通过返回一个MvcHtmlString对象来实现。下面用例子演示一下,在一个Action方法中
public ActionResult Test()
{
ViewBag.Message = "<b>ABC</b>";
return View();
}
在View页面中
@ViewBag.Message
这样子显示出来的并不是加粗的ABC,而是”< b>ABC< /b>”。如果把ViewBag.Message修改为一个MvcHtmlString对象
public ActionResult Test()
{
ViewBag.Message = new MvcHtmlString("<b>ABC</b>");
return View();
}
呈现出来的就是加粗的ABC了,这就是我们想要的结果。
使用MVC框架内置的Helper Method
使用Helper Method创建Form
我们可以这样来创建一个Form
@{Html.BeginForm();}
请输入用户名
<input type="text" id="userName" name="userName" />
<input type="submit" value="Submit" />
@{ Html.EndForm();}
也可以这样来创建一个Form
@using (Html.BeginForm())
{
@:请输入用户名
<input type="text" id="userName" name="userName" />
<input type="submit" value="Submit" />
}
也许你会问,这样子太麻烦了,我直接写一个HTML标签多简单。确实是这样的,不过,Html.BeginForm()这个方法有非常多个重载的版本,如果创建的Form属性比较多的话,可以考虑用它的重载版本,支持路由哦。
使用input元素
MVC框架提供了以下内置的Helper Method,可以生成常用的input元素
<div>
@Html.CheckBox("myCheckBox")
@Html.Hidden("myHidden")
@Html.RadioButton("myRadio", "val", true)
@Html.Password("myPassword")
@Html.TextArea("myTextArea")
@Html.TextBox("myTextBox")
</div>
生成的HTML代码如下
<div>
<input id="myCheckBox" name="myCheckBox" type="checkbox" value="true" />
<input name="myCheckBox" type="hidden" value="false" />
<input id="myHidden" name="myHidden" type="hidden" value="" />
<input checked="checked" id="myRadio" name="myRadio" type="radio" value="val" />
<input id="myPassword" name="myPassword" type="password" />
<textarea cols="20" id="myTextArea" name="myTextArea" rows="2"></textarea>
<input id="myTextBox" name="myTextBox" type="text" value="" />
</div>
使用Helper Method创建列表元素
可以使用下面的两个方法来创建下拉框和多选框
<div>
@Html.DropDownList("myDrowdownList", new SelectList(new[] { "A", "B" }), "请选择")
@Html.ListBox("myList", new MultiSelectList(new[] { "A", "B" }))
</div>
生成的HTML代码为
<div>
<select id="myDrowdownList" name="myDrowdownList">
<option value="">请选择</option>
<option>A</option>
<option>B</option>
</select>
<select id="myList" multiple="multiple" name="myList">
<option>A</option>
<option>B</option>
</select>
</div>
以上所有内置的Helper Method,在强类型视图中都有一个对应的方法,以For结尾的,强类型视图对应的方法,可以通过VS的智能提示框来有效地避免输入字符串时出错。下面我们编写一个例子来演示一下。
在Models文件夹中新建一个名叫Person的类
public class Person
{
public string Name { get; set; }
public string Gender { get; set; }
}
在一个类型为Person的强类型视图,我们可以以下面的方式来使用Helper Method
<div>
@Html.TextBoxFor(s => s.Name)
@Html.DropDownListFor(s => s.Gender, new SelectList(new string[] { "男", "女" }), "请选择")
</div>
生成的HTML代码为
<div>
<input id="Name" name="Name" type="text" value="" />
<select id="Gender" name="Gender">
<option value="">请选择</option>
<option>男</option>
<option>女</option>
</select>
</div>