ASP. NET MVC 4 (vi) HELP function

Source: Internet
Author: User
Tags http post

The Help function encapsulates some code so that we can reuse it in the application, and there are many helper functions built into MVC that make it easy to generate HTML markup. The data model class definitions used in the following example are listed first:

namespace Helpermethods.models {public '    partial class Person {public        int PersonId {get; set;}        public string FirstName {get; set;}        public string LastName {get; set;}        Public DateTime BirthDate {get; set;}        Public Address homeaddress {get; set;}        public bool isapproved {get; set;}        Public role role {get; set;}    }    public class Address {public        string Line1 {get; set;}        public string Line2 {get; set;}        public string City {get; set;}        [Display (Name = "ZIP CODE")]        public string PostalCode {get; set;}        public string Country {get; set;}    }    public enum Role {        Admin,        User,        Guest    }}

Definition of the controller:

namespace Helpermethods.controllers {public    class Homecontroller:controller {public        actionresult Index () { C2/>viewbag.fruits = new string[] {"Apple", "Orange", "Pear"};            Viewbag.cities = new string[] {"New York", "London", "Paris"};            String message = "This was an HTML element: <input>";            Return View ((object) message);        Public ActionResult Createperson () {            return View (new person {Role = role.guest});        [HttpPost]        Public ActionResult Createperson (person person) {            return View (' Displayperson ', person);}}}    

Inline help functions

We can define inline helper functions directly in the view, using the @helper tag inline function definition:

@model string@{    Layout = null;} @helper Listarrayitems (string[] items) {    foreach (string str in items)    {        <b> @str </b>    }} <! DOCTYPE html>

This defines an inline helper function listarrayitems, which we can reuse to display numeric content, and inline helper functions that do not return a value. When we call Listarrayitems, we do not have a type of parameter Cast,mvc automatically implements the type conversion.

External helper functions

While the inline help function is convenient, it can only be defined and used in the view, and if the inline function is complex it makes the view difficult to read clearly, for which we define an external helper function, which is actually a method extension to the HtmlHelper class. The above inline help function is rewritten as an external helper function:

namespace Helpermethods.infrastructure {public    static class Customhelpers {public        static mvchtmlstring Listarrayitems (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 ());}}}    

HtmlHelper exposes properties such as RouteCollection, ViewBag, and viewcontext to facilitate us to obtain data related to the current request. The external helper function finally returns a Mvchtmlstring object whose contents are written directly to the output response. We can use the Custom external helper function in the view as follows:

@model string@using helpermethods.infrastructure@{    Layout = null;} <! DOCTYPE html>@Html. Listarrayitems (string[]) viewbag.fruits)    </div>    <div>        @Html. Listarrayitems ((string[]) viewbag.cities)     </div> <div> Here's the        message:        <p> @Model </p>    

We need to introduce a namespace that defines an external helper function, or it can be defined in/views/web.config for all views. Use @html to invoke the external helper function, which returns an instance of the HtmlHelper class, and also takes argument type conversions when calling external helper functions.

String encoding in the Help function

When using the Help function, we need to pay attention to the problem of HTML encoding, first look at the following question, if we output some HTML tagged strings in the controller action to the view:

Output this string directly in the view:

@model string@{    Layout = null;} <! DOCTYPE html>

The result of the final razor output is:

The "<>" tag in <input> is encoded as a corresponding character rather than an HTML tag, which is for security reasons, preventing the dynamic embedding of HTML tags or even JavaScript scripts. What happens if you export HTML tags from a help function? Look at the following example:

public static mvchtmlstring DisplayMessage (this htmlhelper HTML, string msg) {     string result = String.Format ("This is   The message: <p>{0}</p>, msg); return new mvchtmlstring (result); }

This helper function is called in the view file to output HTML markup:

This is the HTML <input> edit box, this is because our HTML helper function returns the mvchtmlstring is trusted to be safe, the result of the output is no longer HTML encoding. If the Help function returns not mvchtmlstring, it is just a normal string, such as:

The string is then HTML-encoded and does not output the input tag. But the result is that the <p> tag will also be HTML encoded, which is not the result we want, the correct approach is:

We use HTML. Encode () encodes the dynamic content, and the result still returns the Mvchtmlstring object, which avoids the security vulnerabilities caused by Dynamic content embedding and renders the HTML tags that are actually displayed correctly.

Built-in form helper functions

We can create a form directly using the HTML form tag to edit the data to be submitted:

@model helpermethods.models.person@{    viewbag.title = "Createperson";} 

The problem is that you must hardcode the URL of the form submission, and we can actually create a form using the built-in BeginForm help function:

@Html. BeginForm () <div class= "Dataelem" >    <label>PersonId</label>    <input name= " PersonId "Value=" @Model. PersonId "/></div><div class=" Dataelem ">    <label>first name</ label>    <input name= "FirstName" value= "@Model. FirstName"/></div><div class= "Dataelem" >    <label>last name</label>    

BeginForm start a form, EndForm end the form, and actually the more commonly used notation is to use the Razor code block:

@using (Html.BeginForm ()) {    <div class= "Dataelem" >        <label>PersonId</label>        < Input name= "personId" value= "@Model. PersonId"/>    </div>    <div class= "Dataelem" >        < Label>first name</label>        <input name= "FirstName" value= "@Model. FirstName"/>    </div>    <div class= "Dataelem" >        <label>last name</label>        <input name= "lastName" value= "@ Model.lastname "/>    </div>    

@using Create a self-closing form and no longer need to call EndForm. BeginForm with no parameters commits the form to the current action method of the current controller, in addition to the beginform there are many overloaded forms, here are some examples of use:

@using (Html.BeginForm ("Createperson", "Home", new {id = "Myidvalue"}, formmethod.post,new {@class = "personclass", data _formtype= "Person"})) {...}

Here Createperson specifies the controller to which the form is to be submitted, home is the action,new {id = "Myidvalue"} to be submitted to the additional path mapping parameters, FormMethod.Post specifies that the data be submitted using the HTTP POST method, New {@class = "Personclass", data_formtype= "Person"} specifies the properties of the form tag, resulting in the form HTML result:

We can also specify the path mappings used by the form to generate the links that are submitted to them, such as we have registered such a path map:

We use Beginrouteform to create a form and specify the path mapping records to use:

@using (Html.beginrouteform ("Formroute", New {}, FormMethod.Post, new {@class = "Personclass", data_formtype= "Person"}) ) { ...}

The final result is:

Built-in input helper functions

In fact, there is no need to use HTML tags such as <input> to create edit boxes for data, and MVC provides a number of input helper functions:

HTML elements Example Output results
Checkbox Html.checkbox ("MyCheckBox", false)

<input id= "MyCheckBox" name= "MyCheckBox" type= "checkbox" value= "true"/>
<input name= "MyCheckBox" type= "hidden" value= "false"/>

Hidden Html.hidden ("Myhidden", "Val") <input id= "Myhidden" name= "Myhidden" type= "hidden" value= "Val"/>
Radio Html.radiobutton ("Myradiobutton", "Val", True)

<input checked= "Checked" id= "Myradiobutton" name= "Myradiobutton"
Type= "Radio" value= "Val"/>

Password Html.password ("MyPassword", "Val") Html.password ("MyPassword", "Val")
Text Area

Html.textarea ("Mytextarea", "Val", 5, +, NULL)

<textarea cols= "id=" Mytextarea "name=" Mytextarea "rows=" 5 ">
Val</textarea>

Text Box Html.textbox ("MyTextBox", "Val") <input id= "MyTextBox" name= "MyTextBox" type= "text" value= "Val"/>

Each type of input tag function has several overloaded forms that provide additional parameters to specify the attributes of the label. Note that the checkbox generates two input tags, one of which is hidden, because the browser does not submit data when the checkbox is unchecked, and the hidden flag makes MVC get the data even when the check box is not selected.

Use the form in front of the input helper function to write this:

@model helpermethods.models.person@{    viewbag.title = "Createperson";} 

We specify a name for each input field, and MVC will not be able to successfully bind and create model objects if the specified name and one of the property names of the view model are inconsistent, and we can use this alternative:

We don't need to give the field value again, MVC automatically finds the corresponding value from view data, ViewBag, and view model based on the incoming string, such as calling @html.textbox ("DataValue"). MVC view Gets the value from Viewbag.datavalue, @Model. DataValue, using the first found result. More complex points of @html.textbox ("DataValue.First.Name"), MVC search paths are also more:

•  viewbag.datavalue.first.name  viewbag.datavalue["first"]. Name  viewbag.datavalue["First.name"] •  viewbag.datavalue["First" ["Name"]

Similarly, a search stop after the first available value is found, which inevitably results in some performance loss, but makes it easier for us to create an edit form.

Strongly typed input helper function

Each of the basic input helper functions in the previous section has a corresponding strongly typed form, and the strongly typed input helper function can only be used in strongly typed views.

HTML elements Example Output results
Checkbox Html.checkboxfor (x = x.isapproved)

<input id= "isapproved" name= "isapproved" type= "checkbox" value= "true"/>
<input name= "isapproved" type= "hidden" value= "false"/>

Hidden Html.hiddenfor (x = x.firstname) <input id= "FirstName" name= "FirstName" type= "hidden" value= ""/>
Radio Html.radiobuttonfor (x = x.isapproved, "Val") Input id= "isapproved" name= "isapproved" type= "Radio" value= "Val"/>
Password Html.passwordfor (x = X.password) <input id= "Password" name= "Password" type= "Password"/>
Text Area Html.textareafor (x = X.bio, 5, new{}) <textarea cols= "id=" bio "name=" Bio "rows=" 5 ">bio value</textarea>
Text Box Html.textboxfor (x = x.firstname) <input id= "FirstName" name= "FirstName" type= "text" value= ""/>

The strongly typed input helper function uses lambda expressions to extract fields or properties from the view model, and the resulting HTML results are no different from the basic input, just to help us reduce input errors when programming. The above example uses the strongly typed input function as follows:

@model helpermethods.models.person@{    viewbag.title = "Createperson";} 
Select element Help function

MVC provides the following helper functions to generate the Select element for HTML:

HTML elements Example Output results
Drop-down List Html.dropdownlist ("MyList", New SelectList (new [] {"A", "B"}), "Choose")

<select id= "myList" name= "MyList" >
<option value= "" >Choose</option>
<option>A</option>
<option>B</option>
</select>

Html.dropdownlistfor (x = X.gender, new SelectList (new [] {"M", "F"})

<select id= "Gender" name= "Gender" >
<option>M</option>
<option>F</option>
</select>

Multiple-select Html.listbox ("MyList", New Multiselectlist (new [] {"A", "B"})

<select id= "myList" multiple= "multiple" name= "MyList" >
<option>A</option>
<option>B</option>
</select>

Html.listboxfor (x = x.vals, new multiselectlist (new [] {"A", "B"}))

<select id= "Vals" multiple= "multiple" name= "Vals" >
<option>A</option>
<option>B</option>
</select>

The Select Helper function uses the selectlist or multilselectlist parameters, the difference being that the latter creates a select that allows multiple selections. The value used by the Select Helper function is the Ienumerbale type, for example, we want to create a select edit box for an enumeration type:

<div class= "Dataelem" > <label>Role</label> @Html. dropdownlistfor (M = m.role, new SelectList ( Enum.getnames (typeof (HelperMethods.Models.Role))) </div>

HelperMethods.Models.Role is a C # enumeration type, and the result is:

<div class= "Dataelem" > <label>Role</label> <select data-val= "true" data-val-required= "the Role F Ield is required. "  

Data-val and data-val-required two characteristics are related to data validation, later in this article to detailed analysis.

The above is a summary of the contents of the fourth edition of the Apress Pro ASP. NET MVC 4, as described in the original http://www.apress.com/9781430242369.

ASP. NET MVC 4 (vi) HELP function

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.