ASP. NET MVC3 Learning experience-----Forms and HTML helper methods

Source: Internet
Author: User
Tags actionlink

5.1 Use of Forms

5.1.1 Properties of Action and method

A form is a container that contains input elements, including buttons, checkboxes, text boxes, and other elements that enable users to enter information into a page and submit input information to the server. The action attribute tells the browser where to submit the URL, the method attribute to explain how to tell the browser, the default is the Get method

5.1.2Get and Post methods

1, if you do not want the browser to put the input values into the query string, but want to put in the body of the HTTP request, can be used to assign a value of the method Post,post can use to submit credit card information, add albums to the shopping cart or change the password, etc., the POST request will often change the state on the server, Repeat submissions, etc. Post request for write operation

2, GET request all parameters are in the URL, representing the idempotent and read-only operations, will not change the state of the server, can be repeated to the client to send a GET request without adversely affecting, GET request for read operation

Example: Search for music by calculating the value of an action attribute, using the HTML helper method as follows:

@using (Html.BeginForm ("Search", "Storemanager", Formmethod.get)) {

<input type= "text" name= "Q"/>

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

}

5.2HTML helper Methods

The HTML helper method can be called through the view's HTML property. Of course, you can call the URL helper method through the properties of the URL, and invoke the Ajax helper method through Ajax properties, all of which are designed to make the view coding easy.

As mentioned above in the Html.BeginForm () method, the helper method in the background coordinates with the routing engine to generate the appropriate URL. The helper method generates a start tag during the call and returns an IDisposable object that implicitly calls the Dispose method when it executes to the closing curly brace of the using statement, so the helper method generates an end tag.

5.2.1 Automatic Coding

Example: TextArea helper method, used to output HTML elements textarea

@Html. TextArea ("text", "hello<br/>world!");

The use of 5.2.2 auxiliary methods

Another overloaded version of BeginForm

@using (Html.BeginForm ("Search", "Storemanager", formmethod.get,new{target= "_blank"}))

{

<input type= "text" name= "Q"/>

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

}

The overloaded code passes an anonymous class object to the Htmlattributes parameter of the BeginForm method, and each HTML helper method in the ASP. NET. NET MVC Framework has a htmlattributes parameter in one of its overloaded methods. The parameter types for htmlattributes in different versions are idictionary<string,object> helper methods take dictionary entries and create helper methods with these entries to generate element attributes

Set many of the necessary attributes by using the Htmlattributes parameter, such as setting the class property of an element, because class is a C # keyword at this point you need to add @ before class, that is, @class.

The property is also set to a name with hyphens (for example: Data-val), but C # property names with hyphens are not valid, and all auxiliary methods convert the underscore in the property name to hyphens when rendering HTML.

Examples are as follows:

@using (Html.BeginForm ("Search", "Storemanager", Formmethod.get, new

{

target = "blank",

@class = "Green",

Data_validatable = True

}))

{

<input type= "text" name= "Q"/>

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

}

How the 5.2.3 HTML helper method works

Each razor view inherits the HTML properties of the respective base class, and the type of the HTML attribute is system.web.mvc.htmlhelper<t> here, T is a generic parameter that represents the type of model passed to the view. This property provides some methods that can be called in the view, such as: enableclientvalidation (Selective shutdown (open) client authentication)

5.2.4 setting up album editing forms

@using (Html.BeginForm ()) {

@Html. ValidationSummary (True)

<fieldset>

<legend>Album</legend>

<p><input type= "Submit" value= "Save"/></p>

</fieldset>

}

There are two methods used in this view,

1, Html.BeginForm: The method above has been introduced

2, Html.validationsummary: Used to display an unordered list of all validation errors in the Modelstate dictionary, use the Boolean type parameter (TRUE) to tell the helper method to exclude property-level errors, and only show errors related to the model itself in Modelstate Without displaying errors related to the specific model properties.

3. Example:

Modelstate.addmodelerror ("", "This was all wrong!");

Modelstate.addmodelerror ("Title", "What a terrible name!");

Add the above code to render the edit view in an operation of the controller.

The first error is at the model level because there is no key in the code that provides an association error with a specific property.

The second error is an error associated with the property, so this error is not displayed in the View validation summary area

5.2.5 Adding an INPUT element

1, Html.textbox (and Html.textarea)

The invocation form is as follows:

@Html. TextBox ("Title", model.title);

@Html. TextArea ("text", "Hello");

Overloaded version: @Html. TextArea ("text", "Hello World", 10,80,null);

Render as <textarea cols= "", id= "text" name= "text" rows= "ten" >hello world</textarea>

2, HTML. Label

The method returns an <lable/> element and determines the rendered text and attribute values with a string type parameter

Html.label ("Genreid") is as follows: <label for= "Genreid" >Genre</label>

We can find that the text that the label renders is not "Genreid", but rather "Genre" and, where possible, the helper method uses any available model metadata to generate the display content

3, Html.dropdownlist (and Html.listbox)

These two helper methods return a <select/> element, DropDownList, and ListBox multiple selection (setting properties)

The role of the SELECT element:

L display list of optional items

L Display the current value of the field

Down the list requires a collection of SelectListItem objects containing all the options, each of which contains the text, Value, selected property, You can also create your own collection of SelectListItem objects as needed, or you can build them using the SelectList or Multiselectlist helper methods in the framework.

such as: Viewbag.genreid = new SelectList (db. Genres, "Genreid", "Name", album. Genreid);

Viewbag.artistid = new SelectList (db. Artists, "ArtistID", "Name", album. ArtistID);

The SelectList constructor parameter specifies the original collection (the genres table in the database), the property name used as a background value (Genreid), the property name (name) used as the display text, and the value of the current selection

4, Html.validationmessage

When an error occurs in a particular field in the Modelstate dictionary, you can use the Validationmessage method to display the appropriate error message

Example: First add an error to the title property in the model state

Modelstate.addmodelerror ("Title", "What a terrible name!");

In the view page, you can display the error message: @Html. Validationmessage ("Title");

5.2.6 auxiliary methods, models, and view data

1. Use the auxiliary method to give the same name as the value in ViewBag display the price of the text box

such as: In the controller: viewbag.price=10.0;

In the view: @Html. TextBox ("price");

such as: In the controller: Viewbag.album=new album{price=11};

In the view: @Html. TextBox ("Album.price");

2, the auxiliary method relies on the strong type view data also to be able to work well

such as: in the controller: Var album=new album{price=12.0};

In a view (strongly typed): @Html. TextBox ("price");

3. Provide the displayed value to the form helper method

In the controller: Var album=storedb.albums.single (A=>a.albumid==id);

Viewbag.genres=new selectlist (StoreDB.Genres.OrderBy (G=>g.name), "Generid", "Name", album. Genreid);

In a view (strongly typed): @Html. TextBox ("Title", model.title);

5.2.7 Strong Type Auxiliary method

The method needs to pass a lambda expression for it to specify the model properties to render, and the model of the expression must match the model type specified for the view.

Example: @Html. labelfor (M=>m.genreid);

@Html. Dropdownlistfor (m=>m.genreid,viewbag.genres as SelectList)

@Html. Validationmessagefor (M=>m.title)

These strongly typed auxiliary method names are prefixed with a for, and using lambda expressions is an easy way to refactor the code

5.2.8 helper methods and model meta-data

Example: Using the Label helper method to display a LABEL element for a genre selection list

@Html. Label ("Genreid");

And the helper method generates the following markup:

<label for= "Genreid" >genre </label>

Information obtained by the runtime from the DisplayName attribute of the decorated album model when the helper method asks if the runtime has Genreid of available model metadata

[DisplayName ("Genre")]

public int genreid{get;set;}

5.2.9 template-Assisted method

Template-assisted methods in ASP. NET MVC use metadata and templates to build HTML, where metadata includes information about model values (name and type) and model metadata (added through data annotations).

Template-assisted methods have Html.display and Html.editor (respectively, corresponding to strongly-typed methods Html.displayfor and Html.editorfor)

Example: Use the Html.textboxfor helper method to generate the following characteristics for the title property of an album

@Html. Editorfor (M=>m.title);

Both methods generate the same HTML markup, but the Html.editorfor () method is more extensive, and when you use the template helper method, the runtime generates the appropriate editor, adding the following annotation to the title attribute

[DataType (Datatype.multilinetext]

public string Title{get;set;}

After adding, use the Editorfor method to render as:

<textarea class= "Text-box multi-line" >let me go</textarea>

5.2.10 Auxiliary methods and Modelstate

The helper methods used to display the form values also need to interact with modelstate. Modelstate is a by-product of model binding, coarse with all errors detected during model binding, and the original values that the user submits to update the model

5.3 Other input helper methods

5.3.1 Html.hidden

This method is used to render hidden input elements

such as: @Html. Hidden ("Olive", "Love");

After rendering: <input id= "Olive" name= "Olive" type= "hidden" value= "Love"/>

5.3.2html.password

This method is used to render the password field

such as: @Html. Password ("UserPassword")

The strongly typed method is: Html.passwordfor (M=>m.userpassword);

5.3.3 Html.radiobutton

such as: @Html. RadioButton ("Color", "red")

@Html. RadioButton ("Color", "Blue", true ")

Its corresponding strongly-typed method:

@Html. Radiobuttonfor (M=>m.genreid, "1") Rock

At the time of submission, the value to be submitted will be followed

5.3.4 Html.checkbox

checkbox is the only helper method that renders two input elements

such as: @Html. CheckBox ("isdiscouted");

Render as follows: <input id= "isdiscounted" type= "checkbox" value= "true"/>

<input id= "isdiscounted" type= "hidden" value= "false"/>

5.4 Rendering helper methods

Render helper methods can build connections to other resources in your application, or you can build reusable UI fragments called partial views

5.4.1 Html.ActionLink and Html.routelink

The Html.ActionLink auxiliary method renders a hyperlink to another controller operation, using the routing API in the background to generate a URL such as: @Html. ActionLink ("Link Text", "anotheraction")

Then generates: <a href= "/home/anotheraciton" >link text</a>

When a connection is required for an operation that points to a different controller, the following:

@Html. ActionLink ("Link Text", "Index", "Shoppincart");

The first parameter is the Display field, the action name in the second controller, and the third parameter is the controller name.

In the actual application may need to pass an ID value or other parameter value, this time can pass the RouteValueDictionary object also can pass an object to the Routevalues parameter (usually anonymous class), at run time View object's property and use it to build the route value, (attribute name is parameter name, attribute value is argument) Example:

To build a link to the name Olive:

@Html. ActionLink ("Show Love", "Index", "ShoppingCart", new {name= "Olive"},null);

The last parameter of the method is Htmlattributes, which is to set the value of the HTML element by this parameter, which is set to NULL, without setting any attributes, but must be assigned a value for the call to the ActionLink method

The Html.routelink and Html.ActionLink methods follow the same pattern, but the method accepts only the route name and does not accept the controller name and operation name

such as: @Html. RouteLink ("Link Text", new {action= "Anotheraction"})

5.4.2 URL Helper method

The URL helper method is similar to the HTML ActionLink and RouteLink helper methods, but it returns these URLs instead of tokens as strings, with three helper methods: Action, Content, ROUTEURL

As follows:

The action method is similar to the ActionLink method

<span> @Url. Action ("Browse", "Store", new {genre= "Jazz"},null}</span>

Render as:<span>/store/borwse?genre=jazz</span>

The RouteUrl method is similar to the action method but it receives only the route name and does not accept the controller and operation

The content method can convert a relative path in an application to an absolute path, as follows:

<script src= "@Url. Content (" ~/scripts/sdf.js ")" </script>

Use a wavy line as the first character before a string passed as a content method, regardless of where the application is deployed, the helper method can point to the correct resource, and if you do not add a wavy line, the resulting URL is not valid for the location of the application

5.4.3 Html.partial and Html.renderpartial

The Pattial method renders a partial view as a string, which has four overloaded versions, as follows:

public void Partial (string partialviewname);

public void Partial (string partialviewname,object model);

public void Partial (string partialviewname,viewdatadictionary viewData);

public void Partial (string partialviewname,object model,viewdatadictionary viewData);

There's no graduation. Specify the path and file extension for the view, directly as follows:

@Html. Partial ("Albumdisplay");

RenderPartial is similar to the partial method, but RenderPartial does not return a string but writes directly to the corresponding stream, so it is necessary to use @{html.renderpartial ("Albumdisplay");}

The partial method is relatively flexible, and the RenderPartial method is more advantageous than a large number of uses

5.4.4 Html.action and Html.renderaction

The action is to perform a calm controller operation and display the results, and provides more flexibility and importance because the controller operation can build different models that can take advantage of a separate controller context

Renderaction Direct gratifying response streams, such as:

public class mycontroller{

Public ActionResult Index () {return View ();}

[Childactiononly]

Public ActionResult Menu () {var menu=getmenufrom somewhere ();

Return Partialview (menu);

}

The menu operation builds a menus model and returns a partial view with a menu

On the index.cshtml page you can call this

<body> @Html. Action ("menu")

It is important to note that the menu operation uses the Childactiononlyattribute attribute tag, which prevents the runtime from invoking the menu operation directly through the URL, only through action or renderaction. In MVC3, ControllerContext has a ischildaction property, which is true if the action or renderaction operation, or false through the URL operation. At the same time some action filters are different from sub-operations such as: Authorizeattribute and Outputcacheattribute

1. Pass the value to the Renderaction

Because the action method calls the action method, it is possible to specify some additional actions for the target operation,

As follows: Add some items to the menu

① defining a new class: Menuoption

public class menuoption{

public int height{get;set;}

public int width{get;set;}

}

② Modify the menu operation so that it can accept the Menuoption object as a parameter

[Childactiononly]

Public ActionResult Menu (menuoption options)

{

Return Partialview (options);

}

③ menu options can be passed through the action call in the view

@Html. Action ("menu", new {options=new menuoptions{width=400,height=500}});

2, with the actionname characteristics in combination with

The Renderaction method takes precedence over the ActionName attribute value as the name of the operation to invoke. The following notes:

[Childactiononly]

[ActionName ("Coolmenu")]

Public ActionResult Menu (menuoptions options)

{

Return Partialview (options);

}

When calling the Renderaction method, you need to make sure that the operation name is Coolmenu instead of menu.

ASP. NET MVC3 Learning experience-----Forms and HTML helper methods

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.