.NET Framework 4
最后一节演示了一个示例,该示例包括本主题中描述的 HTML 帮助器。
RadioButton 帮助器方法的标记。
Select your favorite color:<br />
<%= Html.RadioButton("favColor", "Blue", true) %> Blue <br />
<%= Html.RadioButton("favColor", "Purple", false)%> Purple <br />
<%= Html.RadioButton("favColor", "Red", false)%> Red <br />
<%= Html.RadioButton("favColor", "Orange", false)%> Orange <br />
<%= Html.RadioButton("favColor", "Yellow", false)%> Yellow <br />
<%= Html.RadioButton("favColor", "Brown", false)%> Brown <br />
<%= Html.RadioButton("favColor", "Green", false)%> Green
HandleForm 操作方法进行处理,从而生成一个显示用户提交的信息的视图。
HomeController 类。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcHtmlHelpers.Controllers { [HandleError] public class HomeController : Controller { public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; List<string> petList = new List<string>(); petList.Add("Dog"); petList.Add("Cat"); petList.Add("Hamster"); petList.Add("Parrot"); petList.Add("Gold fish"); petList.Add("Mountain lion"); petList.Add("Elephant"); ViewData["Pets"] = new SelectList(petList); return View(); } public ActionResult About() { return View(); } public ActionResult HandleForm(string name, string favColor, Boolean bookType, string pets) { ViewData["name"] = name; ViewData["favColor"] = favColor; ViewData["bookType"] = bookType; ViewData["pet"] = pets; return View("FormResults"); } } }
Index 视图。
<h2><%= Html.Encode(ViewData["Message"]) %></h2> <br /><br /> <% using(Html.BeginForm("HandleForm", "Home")) %> <% { %> Enter your name: <%= Html.TextBox("name") %> <br /><br /> Select your favorite color:<br /> <%= Html.RadioButton("favColor", "Blue", true) %> Blue <br /> <%= Html.RadioButton("favColor", "Purple", false)%> Purple <br /> <%= Html.RadioButton("favColor", "Red", false)%> Red <br /> <%= Html.RadioButton("favColor", "Orange", false)%> Orange <br /> <%= Html.RadioButton("favColor", "Yellow", false)%> Yellow <br /> <%= Html.RadioButton("favColor", "Brown", false)%> Brown <br /> <%= Html.RadioButton("favColor", "Green", false)%> Green <br /><br /> <%= Html.CheckBox("bookType") %> I read more fiction than non-fiction.<br /> <br /><br /> My favorite pet: <%= Html.DropDownList("pets") %> <br /><br /> <input type="submit" value="Submit" /> <% } %>
FormResults 视图。
<h2>FormResults</h2> <p> Your name: <b><%= Html.Encode(ViewData["name"])%></b> </p> <p> Your favorite color: <b><%= Html.Encode(ViewData["favColor"]) %></b> </p> <% if (ViewData["bookType"].Equals(true)) { %> <p>You read more <b>fiction</b> than non-fiction.</p> <% } else { %> <p>You read more <b>non-fiction</b> than fiction.</p> <% } %> Your favorite pet: <b><%= Html.Encode(ViewData["pet"]) %></b>