Chapter 1 helper method, Chapter 4 helper

Source: Internet
Author: User

Chapter 1 helper method, Chapter 4 helper

I. Custom helper Method

1. inline helper Method

    Use the @ helper tag, which has the name, parameter, and no return value. The result is directly put in the response of the client. InRuntime evaluation type.

@helper ListArrayItems(string[] items){    <ul>    @foreach (string str in items)    {        <li>@str</li>    }   </ul>}
<Div> fruit here: @ ListArrayItems (ViewBag. Fruits) </div>

2. External helper method (Extension Method)

 public static MvcHtmlString ListArrayItems(this HtmlHelper html , string[] lists)        {             TagBuilder tag= new TagBuilder("ul");            foreach (string str in lists)            {                TagBuilder itemTag = new TagBuilder("li");                itemTag.SetInnerText(str);                tag.InnerHtml += itemTag.ToString();            }            return new MvcHtmlString(tag.ToString());        }
@using HelperMethods.Infrastructure
.......
<Div> City: @ Html. ListArrayItems (string []) ViewBag. Cities) </div>

 

Useful attributes defined by the HtmlHelper class

Attribute Description
RouteCollection Returns the route set defined by the application.
ViewBag Return the View package data and pass it from the Action Method to the view that calls the Helper method.
ViewContext Returns the ViewContext object to access the request details and request processing methods.

Useful attributes defined by the ViewContext class

Attribute Description
Controller Returns the Controller that processes the current request.
HttpContext Returns the HttpContext object that describes the current request.
IsChildAction True when the view is rendered by a sub-action
RouteData Return request route data
View Return the IView implementation instance that has called the Helper method.

Some members of the TagBuilder class

Member Description
InnerHtml Set the element content to an attribute of an HTML string. the value assigned to this attribute is not encoded and can be embedded into an HTML element.
SetInnerText (string) Set the text content of the HTML element. The string parameter is encoded for secure display.
AddCssClass (string) Add a CSS class to the HTML Element
MergeAttribute (string, string, bool) Add a tag attribute to the HTML element. (The parameter is the tag attribute name, value, and whether to replace an existing tag with the same name)

The introduction of namespaces can be stored in/Views/web. config.

    Helper Method: To reduce the amount of repetition in vision, it is only usedSimplest.

    Division View: Used for more complex marking and content

    Sub-action: Used to operate model data. (The Sub-action is recommended when the Helper does not contain only a small number of C # statements or C # statements that are more than HTML elements)

Encode (dangerous) data in the Helper method:

// Selectively encode the data values in the Helper MethodString encodedMsg = html. Encode (msg );String result = string. Format ("here is the information: <p> {0} </p>", encodedMsg); return new MvcHtmlString (result );

2. built-in Form helper Method

1. Create a form Element

Overloading of the inform helper Method

Heavy Load Description
BeginForm () Create a form and pass it back to the source animation method (the action that triggers rendering of the form is legal)
BeginForm (action, controller) Create a form and hand it back to the action method and controller specified in string form
BeginForm (action, controller, method) Create a form, return to the action method and controller specified in the form string, and specify the value of the method label attribute in the form element.
BeginForm (action, controller, method, attributes) Create a form, return to the action method and controller specified in the form string, specify the value of the method tag attribute in the form element, and specify the tag attribute (Object attribute) of the form element)
BeginForm (action, controller, routeValues, method, attributes) Create a form, return to the action method and controller specified in the form string, specify the value of the method tag attribute in the form element, and specify the tag attribute (Object attribute) of the form element ), specify a value for the route fragment variable in the route configuration (the property of the object corresponds to the route variable)
@ Using (Html. beginForm ("CreatePerson", "Home", // Action Method Name, controller name new {id = "MyIdValue"}, // The value of the id segment variable in route configuration FormMethod. post, // value of the method label attribute new {@ class = "personClass", data_formType = "person"} // other label attributes of the form element )) {............ <input type = "submit" value = "submit"/>}
// <Form action = "/Home/CreatePerson/MyIdValue" class = "personClass" data-formType = "person" method = "post">

Data_formType = "person" is automatically mapped to data-formType = "person"

  Specify the form to use the route:

@ Using (Html. beginRouteForm ("Default", // route name new {id = "MyIdValue"}, // The value of the id segment variable in route configuration FormMethod. post, // new {@ class = "personClass", data_formType = "person"} // other tag attributes of the form element )){

2. Input helper

Basic Input HTML helper (strong type results are not output, similar)

HTML Element Example Output
Checkbox (check box)
@Html.CheckBox("myCheckbox", false)
@Html.CheckBorFor(x=>x.myCheckbox)

<Input id = "myCheckbox" name = "myCheckbox" type = "checkbox" value = "true"/>

<Input name = "myCheckbox" type = "hidden" value = "false"/>

Hidden field (Hidden field)
@Html.Hidden("myHidden", "val")
@Html.HiddenFor(x=>x.myCheckbox)
<Input id = "myHidden" name = "myHidden" type = "hidden" value = "val"/>
Radio button (single choice button)
@Html.RadioButton("myRadioButton", "val", true)
@Html.RadioButtonFor(x=>x.myRadioButton, "val")
<Input checked = "checked" id = "myRadioButton" name = "myRadioButton" type = "radio" value = "val"/>
Password (Password box)
@Html.Password("myPassword", "val")
@Html.PasswordFor(x=>x.myPassword)
<Input id = "myPassword" name = "myPassword" type = "password" value = "val"/>
Text area)
@Html.TextArea("myTextArea", "val", 5, 20, null)
@Html.TextAreaFor(x=>x.myTextArea, 5,20,new{})
<Textarea cols = "20" id = "myTextArea" name = "myTextArea" rows = "5">
Text box)
@Html.TextBox("myTextBox", "val")
@Html.TextBoxFor(x=>x.myTextBox)
<Input id = "myTextBox" name = "myTextBox" type = "text" value = "val"/>
Select Element
Drop-down list)  
@ Html. DropDownList ("myList", new SelectList (new [] {"A", "B"}), "select ")

<Select id = "myList" name = "myList">

<Option value = ""> select </option>
<Option> A </option>
<Option> B </option>
</Select>

Drop-down list (strong type Drop-down list)
 @Html.DropDownListFor(m=>m.Gender,  new SelectList(new[]{"M","F"}))        

<Select id = "Gender" name = "Gender">
<Option> M </option>
<Option> F </option>
</Select>

Related Article

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.