Rendering a Form in ASP.NET MVC Using HTML Helpers

本文档介绍了ASP.NET MVC框架中常用的HTML助手方法,包括BeginForm、CheckBox、DropDownList、RadioButton和TextBox等。通过实例展示了如何使用这些助手来简化HTML表单的创建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://msdn.microsoft.com/en-us/library/dd410596(v=vs.100).aspx

更多:http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper(v=vs.118).aspx

如何创建自定义html helper:http://www.asp.net/mvc/tutorials/older-versions/views/creating-custom-html-helpers-cs

The ASP.NET MVC framework includes helper methods that provide an easy way to render HTML in a view. This topic explains how to work with the most frequently used HTML helpers. The last section shows an example that incorporates the HTML helpers described in this topic.

Available HTML Helpers

The following list shows some of the currently available HTML helpers. The helpers listed with an asterisk (*) are demonstrated in this topic.

  • ActionLink — Links to an action method.

  • BeginForm * — Marks the start of a form and links to the action method that renders the form.

  • CheckBox * — Renders a check box.

  • DropDownList * — Renders a drop-down list.

  • Hidden — Embeds information in the form that is not rendered for the user to see.

  • ListBox — Renders a list box.

  • Password — Renders a text box for entering a password.

  • RadioButton * — Renders a radio button.

  • TextArea — Renders a text area (multi-line text box).

  • TextBox * — Renders a text box.

Using the BeginForm Helper

The BeginForm helper marks the start of an HTML form and renders as an HTML form element. The BeginForm helper method has several overrides. The version of the BeginForm helper shown in the following example takes two parameters, the names of the action method and the controller to submit the form. The BeginForm helper implements the IDisposableinterface, which enables you to use the using keyword (Using in Visual Basic), similar to ASP.NET AJAX usage.

The following example shows how to use the BeginForm helper in a using pattern.

C#
VB
<% using(Html.BeginForm("HandleForm", "Home")) %>
<% { %>
    <!-- Form content goes here -->
<% } %>

You can also use the BeginForm helper declaratively. The difference between using BeginForm declaratively and using an HTML form tag is that BeginForm assigns default value for the action method and action attributes, which simplifies the markup. The following example uses declarative markup to mark the start and ending of a form.

C#
VB
<% Html.BeginForm(); %>
    <!-- Form content goes here -->
<% Html.EndForm(); %>

Using the CheckBox Helper

The CheckBox helper method renders a check box that has the name that you specify. The rendered control returns a Boolean value (true or false). The following example shows markup for the CheckBox helper method.

<%= Html.CheckBox("bookType") %>

Using the DropDownList Helper

The DropDownList helper renders a drop-down list. In its simplest form, DropDownList takes one parameter, the name of the ViewData key whose value is of type SelectList and that contains the option values for the drop-down list. The MVC framework uses the ModelState property of ViewData to determine the selected value. If the ModelState property is empty, the framework looks for an item whose Selected property is set.

The following example shows markup for the DropDownList helper method.

<%= Html.DropDownList("pets") %>
NoteNote

Both the DropDownList and ListBox helpers accept either a SelectList or MultiSelectList object.

The following code is a part of an Index action method in which values are added to a List object. The List object is passed to an instance of SelectList, which is then added to the ViewData object.

C#
VB
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);


Using the RadioButton Helper

The RadioButton helper method renders a radio button. In its simplest form, the method takes three parameters: the name of the control group, the option value, and a Boolean value that determines whether the radio button is selected initially. The following markup shows markup for the RadioButton helper method.

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

Using the TextBox Helper

The TextBox helper method renders a text box that has the specified name. The following markup shows markup for theTextBox helper method.

Enter your name: <%= Html.TextBox("name") %>

Example Application

The following example is a complete example from which the previous examples where taken. The Index page displays a form that implements HTML helper methods. When the user submits the form, the form is handled by the HandleForm action method, which generates a view that displays the information that the user submitted.

The following example shows the HomeController class.

C#
VB
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");
        }
    }
}


The following example shows the Index view.

C#
VB
<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" />
<% } %>


The following example shows the FormResults view.

C#
VB
<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>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值