ASP. NET MVC3 learning experience ----- auxiliary methods of form and HTML

Source: Internet
Author: User
Tags actionlink

Use of forms
Features of action and method
A form is a container containing input elements, including buttons, check boxes, and text boxes. These input elements allow users to enter information on the page and submit the input information to the server. The Action feature tells the browser where to submit the URL, and the method feature tells the browser how to use it. The default method is get.
Get and Post Methods
1. If you do not want the browser to put the input value in the query string, but want to put it in the body of the HTTP request, you can assign a post value to the method, post can be used to submit credit card information, add an album to the shopping cart, or change the password. post requests usually change the status on the server and submit it repeatedly. POST requests are used to write www.2cto.com
2. All parameters of the Get request are in the URL, which indicates idempotent operations and read-only operations and does not change the server status, you can repeatedly send GET requests to the client without any negative impact. GET requests are used for read operations.
Example: search for music by calculating the Action feature value. The following is an example of how to search for music by using HTML:
@ Using (Html. BeginForm ("Search", "StoreManager", FormMethod. Get )){
<Input type = "text" name = "q"/>
<Input type = "submit" value = "Search"/>
}
5.2HTML auxiliary Method
The HTML auxiliary method can be called through the Html attribute of the view. Of course, you can also call the Url-assisted method through the URL attribute and call the Ajax-assisted method through the AJAX attribute. All these methods aim to make view encoding easier.
As mentioned in the preceding Html. BeginForm () method, in the background, the auxiliary method is coordinated with the routing engine to generate a suitable URL. This auxiliary method generates a starting label during the call and returns an IDisposable object. When the end curly braces of the using statement are executed, the Dispose method is called implicitly, therefore, this auxiliary method generates an end tag.
Automatic Encoding
Example: TextArea auxiliary method, used to output the HTML element textarea
@ Html. TextArea ("text", "hello <br/> world! ");
Use of 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"/>
}
This overload code transmits an anonymous Class Object to the htmlAttributes parameter of the BeginForm method. in the net mvc framework, each HTML auxiliary method has an htmlAttributes parameter in one of its overload methods. In different versions, the parameter type of htmlAttributes is IDictionary <string, object> auxiliary methods use dictionary entries and use these entries to create auxiliary methods to generate element features
You can use the htmlAttributes parameter to set many necessary features, such as setting the class attribute of an element. Because the class is a C # keyword, you need to add @ before the class, that is, @ class.
In addition, the attribute is set to a name with a hyphen (for example, data-val), but the C # attribute name with a hyphen is invalid, all auxiliary methods convert the underline in the attribute name to a hyphen when rendering HTML.
Example:
@ 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 HTML auxiliary methods work
Each Razor view inherits the Html attributes of its own base class. The type of the Html attribute is System. web. mvc. htmlHelper <T> here T is a generic parameter, representing the model type passed to the view. This attribute provides some methods that can be called in the view, such: enableClientValidation (disable (enable) Client Authentication)
Set the album editing form
@ Using (Html. BeginForm ()){
@ Html. ValidationSummary (true)
<Fieldset>
<Legend> Album </legend>
<P> <input type = "submit" value = "Save"/> </p>
</Fieldset>
}
Two methods are used in this view,
1. Html. BeginForm: This method is already described above.
2. Html. validationSummary: used to display the unordered list of all verification errors in the ModelState dictionary. The Boolean parameter (true) is used to notify the auxiliary method to exclude Attribute-level errors, only errors related to the Model in ModelState are displayed, but errors related to specific model attributes are not displayed.
3. Example:
ModelState. AddModelError ("", "This is all wrong! ");
ModelState. AddModelError ("Title", "what a terrible name! ");
Add the above Code to an operation of the Controller to render and edit the view,
The first error is at the model level, because the Code does not provide a key for association errors and specific attributes,
The second error is an attribute-related error. Therefore, this error is not displayed in the view verification Summary Area.
Add input element
1. Html. TextBox (and Html. TextArea)
The call method is as follows:
@ Html. TextBox ("Title", Model. Title );
@ Html. TextArea ("text", "Hello ");
Overloaded version: @ Html. TextArea ("text", "hello world", 10, 80, null );
Rendered as <textarea cols = "80", id = "text" name = "text" rows = "10"> hello world </textarea>
2. HTML. Label
This method returns a <lable/> element, and uses string parameters to determine the rendered text and feature values.
Html. Label ("GenreId"): <label for = "GenreId"> Genre </label>
We can find that the text rendered by the label is not "GenreId", but "Genre". When possible, the Helper method uses any available model metadata to generate the display content.
3. Html. DropDownList (and Html. ListBox)
Both of these auxiliary methods return a <select/> element, one DropdownList choice, and multiple ListBox selections (attributes need to be set)
The role of the Select element:
L display the list of optional items
L display the current field value
The list requires a set of SelectListItem objects that can be Selected. Each SelectListItem object contains the Text, Value, and Selected attributes. You can also create a set of SelectListItem objects as needed, you can also use the SelectList or MultiSelectList auxiliary method in the framework to build the image.
For example, 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 set (Genres table in the database), used as the property Name (GenreId) for the background value, and used as the property Name (Name) for the display text) and the value of the selected item.
4. Html. ValidationMessage
When an error occurs for a specific field in the ModelState dictionary, you can use the ValidationMessage method to display the error message.
For example, add an error for the Title attribute in the model status.
ModelState. AddModelError ("Title", "what a terrible name! ");
The view page displays the following error message: @ Html. ValidationMessage ("Title ");
Auxiliary methods, models, and view Data
1. Assign the price of the text box with the same name as the value in Viewbag through the auxiliary Method
For example, in the Controller: ViewBag. Price = 10.0;
In the View: @ Html. TextBox ("Price ");
For example, in the Controller: ViewBag. Album = new Album {Price = 11 };
In the View: @ Html. TextBox ("Album. Price ");
2. The auxiliary methods can work well with strong-type view data.
For example, 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 auxiliary 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 );
Auxiliary method of strong type
This method needs to pass a lambda expression for it to specify the model attribute to be rendered, and the model of the expression must be consistent with 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 strong auxiliary method names all use For as their suffixes. Using lambda expressions can easily implement code refactoring.
Auxiliary methods and model metadata
For example, use the Label auxiliary method to display a label element for the genre selection list.
@ Html. Label ("GenreId ");
The auxiliary method generates the following mark:
<Label for = "GenreId"> Genre </label>
The information obtained from the Displayname feature for decorating the Album model when the auxiliary method asks whether GenreId has the metadata of the available model at runtime.
[DisplayName ("Genre")]
Public int GenreId {get; set ;}
Template auxiliary Method
Templates in ASP. net mvc use metadata and templates to construct HTML. Metadata includes information about model values (names and types) and model metadata (added through data annotations.
Template-assisted methods include Html. Display and Html. Editor (corresponding to strong Methods Html. DisplayFor and Html. EditorFor respectively)
For example, Html. TextBoxFor is used to generate the following features for the Title attribute of an album.
@ Html. EditorFor (m => m. Title );
The two methods generate the same HTML tag, but the Html. the EditorFor () method is more widely used. When using the template-assisted method, you can generate an appropriate "Editor" at runtime, and add the following annotations on the Title attribute.
[DataType (DataType. MultilineText]
Public string Title {get; set ;}
After being added, use the EditorFor method to render it:
<Textarea class = "text-box multi-line"> Let me go </textarea>
Auxiliary methods and ModelState
The auxiliary method used to display the form value also needs to interact with ModelState. ModelState is a by-product of model binding. It contains all errors detected during model binding and the original values submitted by the user to update the model.
Other input auxiliary methods
Html. Hidden
This method is used to render hidden input elements.
For example: @ Html. Hidden ("Olive", "Love ");
After rendering: <input id = "Olive" name = "Olive" type = "hidden" value = "Love"/>
2Html. Password
This method is used to render the password field
For example: @ Html. Password ("UserPassword ")
The strongly typed method is Html. PasswordFor (m => m. UserPassword );
5.3.3 Html. RadioButton
For example: @ Html. RadioButton ("color", "red ")
@ Html. RadioButton ("color", "blue", true ")
The corresponding strongly typed method:
@ Html. RadioButtonFor (m => m. GenreId, "1") Rock
Values to be submitted after submission
Html. CheckBox
CheckBox is the only auxiliary method for rendering two input elements.
For example: @ Html. CheckBox ("IsDiscouted ");
Rendering: <input id = "IsDiscounted" type = "checkbox" value = "true"/>
<Input id = "IsDiscounted" type = "hidden" value = "false"/>
Rendering assistance Method
The rendering assistant method can generate connections to other resources in the application, or build reusable UI fragments called partial views.
Html. ActionLink and Html. RouteLink
Html. ActionLink is used to render a hyperlink pointing to another controller operation. In the background, use the routing API to generate a URL such as @ Html. ActionLink ("Link Text", "AnotherAction ")
Generated: <a href = "/Home/AnotherAciton"> Link Text </a>
When you need a connection to different controllers:
@ Html. ActionLink ("Link Text", "Index", "ShoppinCart ");
The first parameter is the display field, the operation name in the second controller, and the third parameter is the controller name.
In actual applications, you may need to pass an ID value or other parameter values. In this case, you can pass a RouteValueDictionary object or an object (usually an anonymous class) to the routeValues parameter ), view the attributes of an object at run time and use it to construct the route value (the attribute name is a parameter name and the attribute value is a parameter). For example:
To construct a link pointing to Olive:
@ Html. ActionLink ("Show Love", "Index", "ShoppingCart", new {name = "Olive"}, null );
The last parameter of this method is htmlAttributes, that is, the value of the HTML element is set through this parameter. If it is set to null above, no features are set, but it must be assigned a value to call the ActionLink method.
The Html. RouteLink and Html. ActionLink methods follow the same mode. However, this method only accepts the route name, not the Controller name and operation name.
Example: @ Html. RouteLink ("Link Text", new {action = "AnotherAction"}) URL helper Method
The URL-assisted method is similar to the ActionLink and RouteLink-assisted methods of HTML, But it returns these URLs in the form of strings instead of tags. There are three auxiliary 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>
Rendered as: <span>/Store/Borwse? Genre = Jazz </span>
The RouteUrl method is similar to the Action method, but it only receives the route name and does not accept the controller and operation.
The Content method can convert relative paths in the application to absolute paths, as follows:
<Script src = "@ Url. Content ("~ /Scripts/sdf. js ")" </script>
The Tilde line is used as the first character before the string passed as the Content method. No matter where the application is deployed, the secondary method can point to the correct resource. If the Tilde line is not added, if the location of the app is moved, the generated URL does not exist.
Html. Partial and Html. RenderPartial
The Pattial method renders the partial view into a string. This method has four overloaded versions, as shown below:
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 is no graduation to specify the path and file extension for the view, directly as follows:
@ Html. Partial ("AlbumDisplay ");
RenderPartial is similar to Partial, but RenderPartial is not a returned string but directly written to the corresponding stream. Therefore, you need to use @ {Html. RenderPartial ("AlbumDisplay ");}
The Partial method is relatively flexible, and the RenderPartial method is more advantageous than a large amount of use.
Html. Action and Html. RenderAction
Action is to execute a Light Controller operation and display the results, and provides more flexibility and importance, because the Controller operation can create different models, you can use a separate controller Context
RenderAction directly responds to the stream, for example:
Public class MyController {
Public ActionResult Index () {return View ();}
[ChildActionOnly]
Public ActionResult Menu () {var menu = GetMenuFrom SomeWhere ();
Return PartialView (menu );
}
Create a Menu model by using the Menu operation and return the partial view with the Menu
On the Index. cshtml page, you can call
<Body> @ Html. Action ("Menu") Note that the Menu operation uses the ChildActionOnlyAttribute feature flag. This feature setting prevents the Menu operation from being called directly through the URL during running, and can only be operated through Action or RenderAction. In MVC3, ControllerContext has an IsChildAction attribute. If an Action is performed by Action or RenderAction, the attribute is true, and the parameter is false by URL. At the same time, some operation filters are different from sub-operations such as AuthorizeAttribute and OutputCacheAttribute.
1. Pass the value to RenderAction
Because the operation method calls the operation method, you can specify some additional operations for the target operation,
Add some items to the menu as follows:
① Define 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 be used as a parameter to accept the MenuOption object
[ChildActionOnly]
Public ActionResult Menu (MenuOption options)
{
Return PartialView (options );
}
③ In the view, you can use Action to call the menu option.
@ Html. Action ("Menu", new {options = new MenuOptions {width = 400, Height = 500 }});
2. Combined with the ActionName feature
The RenderAction method preferentially uses the ActionName attribute value as the name of the operation to be called. Note the following:
[ChildActionOnly]
[ActionName ("CoolMenu")]
Public ActionResult Menu (MenuOptions options)
{
Return PartialView (options );
}
When calling the RenderAction method, make sure that the operation name is CoolMenu rather than Menu.

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.