ASP.NET 3.5 MVC 架构与实战笔记6 HtmlHelper控件解析

FormExtensions类

FormExtensions类是一个静态类,定义了3种类型的扩展方法:BeginForm、BeginRouteForm、EndForm;在实际开发中,也可以使用using语句,而不需要写EndForm扩展方法。

InputExtensions类

InputExtensions类定义了5种类型的扩展方法:CheckBox,Hidden,Password,RadioButton,TextBox.

    <%=Html.BeginForm("CheckBox", "Study")%>
    <fieldset>
        <legend>CheckBox</legend>
        <%=Html.CheckBox("MyCheckBox1",true,new{>%>
        <label for="checkbox1">XieTi</label>
        
        <%= Html.CheckBox("MyCheckBox2",false,new {>%>
        <label for="checkbox2">HeiTi</label>
        
        <br/><br/>
        <input type="submit" value="submit" />
    </fieldset>
    <% Html.EndForm();%>

看看运行后的网页源代码吧:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>
        TestPage
</title></head>
<body>
    <div>
    <form action="/Study/Index" method="post">System.Web.Mvc.Html.MvcForm
    <fieldset>
        <legend>¨¦¨¨??CheckBox</legend>
        <input checked="checked"  name="MyCheckBox1" type="checkbox" value="true" /><input name="MyCheckBox1" type="hidden" value="false" />
        <label for="checkbox1"></label>
        
        <input  name="MyCheckBox2" type="checkbox" value="true" /><input name="MyCheckBox2" type="hidden" value="false" />
        <label for="checkbox2"></label>
        
        <br/><br/>
        <input type="submit" value="submit" />
    </fieldset>
    </form>
    </div>
</body>
</html>

对于每一个CheckBox控件,MVC都另外生成了一个隐藏的对应控件

<input name="MyCheckBox1" type="hidden" value="false" /><input name="MyCheckBox2" type="hidden" value="false" />

所以在控制器中检测复选框的状态,可以使用如下代码:

        public ActionResult  CheckBox(FormCollection formCollection)
        {
            bool myCheckBox1 = formCollection[0].Contains("true");
            bool myCheckBox2 = formCollection["checkBox2"].Contains("true");

            ViewData["MyCheckBox1"] = myCheckBox1;
            ViewData["MyCheckBox2"] = myCheckBox2;

            return View("Test");

        }

Password扩展方法主要实现输入密码的文本框

RadioButton主要实现单选按钮控件

TextBox主要实现单行的文本框

LinkExtensions类

ActionLink,RouteLink

RenderPartialExtensions类

在视图中显示相关的用户控件

SelectExtensions类

:DropDownList,ListBox

TextAreaExtensions类

:设置TextArea控件

ValidationExtensions类

:实现控件的输入验证 ValidationMessage, ValidationSummary