The HtmlHelper of MVC

Source: Internet
Author: User
Tags actionlink

Since the study of MVC, HtmlHelper use is also very much, the following began to summarize, because I am more lazy, most of the content from Slark.net notes,

Someone asked why with this htmlhelper, I like to use the original label, this according to personal habits, but the existence is the truth, Microsoft has encapsulated you, simple and easy to expand, why not use it, then let's start.

1,actionlink

@Html. ActionLink ("LinkText", "ActionName") @Html. ActionLink ("LinkText", "ActionName", "Controllername") @ Html.ActionLink ("LinkText", "ActionName", new {id = 1})

Click View in the browser. Operation Result:

<a href= "/defaultcontroller/actionname" >LinkText</a>   //Use current controller default Controller<a href= "/ Controllername/actionname ">LinkText</a>      /Use specified controller<a href="/defaultcontroller/actionname/ 1 ">LinkText</a>

2,routelink, this is not a lot of use, just copy the example here.

RouteLink is also used to generate <a> tags in html, but its parameters and ActionLink are different. Here we give the RouteLink code that can implement the above three lines of HTML code:

@Html. RouteLink ("LinkText", new {action = "ActionName"}) @Html. RouteLink ("LinkText", new {action = "actionname", control Ler = "Controllername"}) @Html. RouteLink ("LinkText", new {action = "actionname", id = 1})

As you can see from the above code, Linktext is still the text that the link displays, and the other information for the link is contained in the second parameter of RouteLink. This parameter is an object whose Action property represents the action pointed to, and the Controller property represents the controller to which it is pointing. If no controller attribute is present, point to the current controller. The id attribute is the parameter to be passed.

3,textbox,hidden,password these three kinds of usage is similar, directly lists to

@Html. TextBox ("NameId") @Html. TextBox ("NameId", "Value")
@Html. Hidden ("NameId") @Html. Hidden ("NameId", "Value")
@Html. Password ("NameId") @Html. Password ("NameId", "Value")

4, here is a special description of the use of Html.checkbox

@Html. CheckBox ("NameId", True) @Html. CheckBox ("NameId", false)
<input checked= "Checked" id= "NameId" name= "NameId" type= "checkbox" Value= "true"/><input name= "NameId" type= " Hidden "value=" false "/><input id=" NameId "name=" NameId "type=" checkbox "Value=" true "/><input name=" NameId "type=" hidden "value=" false "/>

Originally, normally it should only generate a label for <input type= "checkbox" > if the checkbox second parameter is true then there is a checked= "checked" attribute that indicates this box ticked. But why does this tag have value= "true" and a tail <input name= "NameId" type= "hidden" value= "false"/>?

Because in our ASP. NET MVC, the effect is: If the checkbox is ticked, then the commit will be passed to the target page a nameid= "true" value, if not ticked will be passed a nameid= "false" value. This value is passed by <input name= "NameId" type= "hidden" value= "false"/>. If there is no <input name= "NameId" type= "hidden" value= "false"/> This paragraph, if the tick and then commit, will still be passed to the target page a nameid= "true" value, Without a tick, the value of NameID is not passed.

5,

RadioButton will generate a <input type= "Radio" > tag with the following code:

@Html. RadioButton ("NameId", "value", true) @Html. RadioButton ("NameId", "value", false)

The generated code is as follows:

<input checked= "Checked" id= "NameId" name= "NameId" type= "Radio" value= "value"/><input id= "NameId" Name= " NameId "type=" Radio "value=" value "/>

You can see that the RadioButton and the checkbox have checked parameters, and radiobutton a value parameter can be set.

6,

The DropDownList function creates a drop-down menu that is represented by a <select> tag. Before creating the drop-down menu, we need to create a list of menu options that are represented by the <option> tag, and create the following method:

@{        selectlistitem Item;        list<selectlistitem> list = new list<selectlistitem> ();        for (int i=1;i<5;i++)        {            item = new SelectListItem ();            Item. Text = "text" + i;            Item. Value = "value" + i;            Item. Selected = (i==2);            List. ADD (item);        }       }

The SelectListItem class generates a menu item whose Text property represents the text it displays, the Value property represents its corresponding values, and the selected property indicates whether it is selected. The above code generates a number of <option> tags and when i is 2 o'clock, the label is selected.

The following code allows you to generate a drop-down menu with a list of the above options:

@Html. DropDownList ("NameId", list)

The resulting results are as follows:

<select id= "NameId" name= "NameId" >    <option value= "Value1" >Text1</option>    <option Selected= "Selected" value= "Value2" >Text2</option>    <option value= "Value3" >Text3</option>    <option value= "Value4" >Text4</option></select>

The first parameter of the visible DropDownList function is its ID and name, and the second parameter is a list of its four options. Each option has its own text, Value, and the second option is selected.

7,

ListBox can generate a multi-select list box, corresponding to the HTML <select multiple= "multiple" > tags, the structure of the listbox and DropDownList structure basically the same, just more multiple= " Multiple "property. We still use the list of options created above to create our listbox with the following code:

@Html. ListBox ("NameId", list)

The resulting results are as follows:

<select id= "NameId" multiple= "multiple" name= "NameId" >    <option value= "Value1" >Text1</option>    <option selected= "selected" value= "Value2" >Text2</option>    <option value= "Value3" >text3 </option>    <option value= "Value4" >Text4</option></select>

8, in addition to the above tags, there is a common method for these generated tags plus attributes

For example, to add a class and style to a tag, you can use the following method:

@Html. TextBox ("NameId", "Value", new {@class = "Classtext", @style = "width:200px"})

The results were as follows:

<input class= "Classtext" id= "NameId" name= "NameId" style= "width:200px" type= "text" value= "value"/>

The yellow marked section above is the added attribute. In fact, you can add any property name and attribute value in the same way, and it will take effect.

9,form form

Generating a form form in HtmlHelper uses two functions: BeginForm and EndForm. There are two ways to generate a <form>...</form> form, using the following method:

@using (Html.BeginForm ("ActionName", "Controllername", Formmethod.get)) {    @Html. TextBox ("NameId")    < Input type= "Submit" value= "Submitbutton"/>}@{html.beginform ("ActionName", "Controllername", FormMethod.Post);}    @Html. TextBox ("NameId")    <input type= "Submit" value= "Submitbutton"/>@{html.endform ();

Look closely at the difference between the two methods of generating form: The first method puts the Html.BeginForm () function into the @using () {} structure, which can directly generate the start and end tags of the form; the second method writes Html.BeginForm () The function generates a start tag, and then the last write Html.endform () function generates the end tag. These two methods produce the same result. The results are as follows:

<form action= "/controllername/actionname" method= "Get" >
<input id= "NameId" name= "NameId" type= "text" value= ""/>
<input type= "Submit" value= "Submitbutton"/></form>
<form action= "/controllername/actionname" method= "POST" > <input id= "NameId" name= "NameId" type= "text" value= ""/> <input type= "Submit" value= "Submitbutton"/></form>

You can see from the running result that the first parameter of BeginForm () specifies the name of the action, the second parameter specifies the name of the controller, and the third parameter specifies whether the post method or the Get method is used when committing. The first form in the code above uses the Get method, and the second form uses the Post method.

In fact, what parameters can not be specified, directly with the default of this page submission, submit mode post

@using (Html.BeginForm ()) {      // content   }

10, using Tagbuilder to extend the HtmlHelper method

Using System.web.mvc;public static class htmlextensions{public    static mvchtmlstring Submit (this htmlhelper helper, String value)    {        var builder = new Tagbuilder ("input");        Builder. Mergeattribute ("type", "submit");        Builder. Mergeattribute ("value", value);                
}
}

Let's take a look at the code above:

    • First of all, to use Tagbuilder will introduce SYSTEM.WEB.MVC class library.
    • Then we look at the parameters of this function, this HtmlHelper helper guarantees that this method will be added to the HtmlHelper, and string value corresponds to the text displayed by the future Commit button, which is the Value property.
    • var builder = new Tagbuilder ("input"), which sets the name of the tag we created as input.
    • The Mergeattribute function adds attributes to the created element, such as Mergeattribute ("type", "submit"), which is added to the type= "submit" attribute.
    • Tagrendermode.selfclosing makes the generated label self-closing, which means there is <input/> this form.
    • Finally, Mvchtmlstring is used as the return value so that the return value is not escaped, such as "<" will not be converted to "&lt". That's what we don't want to see.

We then write the following code in the view to call the function we just wrote:

@Html. Submit ("Submitbutton")

The resulting results are as follows:

<input type= "Submit" value= "Submitbutton"/>

You can see that the tag names, attributes, and self-inclusions that we set in the function are all done. This allows us to successfully generate a self-created submit button.

The HtmlHelper of MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.