HTML-assisted method of MVC and mvchtml

Source: Internet
Author: User
Tags actionlink

HTML-assisted method of MVC and mvchtml

As the name suggests, the HTML Helper method (HTML Helper) is used to help generate HTML. During View development, many HTML tags will be faced, and the processing of these HTML tags is very complicated, to reduce the complexity of the View, you can use HTML-assisted methods to help you generate some HTML tags or content. Because these HTML tags have fixed standard syntax, You can package them into HTML-assisted methods, this allows View development to be faster and avoids unnecessary syntax errors.

ASP. net mvc has many built-in HTML helper methods. These HTML helper methods use the extension feature of C #3.0 to expand various HTML helper methods into the HtmlHelper class, and have multiple loads.

The explanation of HTML-assisted methods can effectively help you face common but tedious HTML coding tasks, such as hyperlinks and form declarations (<form>), form elements (<input>, <select>, <textarea>), HTML encoding and decoding, loading other Partial View pages), Display Error information of Model verification failure, write ASP. net mvc must be indispensable.

1. Output hyperlinks using HTML-assisted Methods

When developing a View page, the most common HTML auxiliary method is the output hyperlink, which outputs ASP in the View. net mvc hyperlinks usually use Html. the ActionLink auxiliary method, which is used to generate text links. The text part of the method is automatically HTML encoded (HtmlEncode ). The usage is as follows.

Syntax example Description
@ Html. ActionLink ("link text", "ActionName ") This is the most basic usage. The controller to jump to is the controller of this view. The link text cannot be a null String, a blank string, or a null Value. Otherwise, The exception of The Value cannot be null or empty is thrown.
@ Html. ActionLink ("link text", "ActionName", "ControllerName ") Link text, action, Controller
@ Html. ActionLink ("link text", "ActionName", new {id = 123, page = 5 }) When you need to set an additional RouteValue, You can input the object-type data in the third parameter.
@ Html. ActionLink ("link text", "ActionName", null, new {@ class = "btnLink "})

When you need to input Additional HTML attributes of a hyperlink, you can load the fourth parameter.

Note: Because the class attribute name is used when the CSS style type is applied in HTML tags, and the class in C # is a keyword, the @ class method must be used, make sure that C # is correctly compiled.

In addition, if you want to output HTML attributes including minus signs (-), such as the data-value attribute, you should use underscores (_) instead.

@ Html. ActionLink ("link text", "ActionName", "ControllerName", null, new {@ class = "btnLink "})

Five parameters

Use Html. acionLink (), the first parameter is the display text of the hyperlink. This parameter cannot be an empty string, a blank string, or a null value, otherwise, The system runs The Value cannot be null or empty exception.

If you want to design an image button that contains a hyperlink, you can use the <a> hyperlink label to output it, and add a background image through CSS, as shown below.

<a href="@Url.Action("ActionName")" class="lnkButton"></a>

ASP. net mvc has another Html. RouteLink auxiliary method. Its usage is very similar to that of Html. ActionLink. The difference is that the input parameters are mainly RouteValue.

 

2. Output A form using HTML-assisted Methods

(1) generate form elements

Before using the form, you should have read the Html several times. beginForm () is used to generate <form> tags, which can be used by using syntax or Html. use EndForm () to generate an appropriate </form> form end. The following are examples of code for Html. BeginForm.

A. Generate form tags using syntax

@using(Html.BeginForm("About","Home")) //Parameter 1:actionName Parameter 2: controllerName
{
     @Html.TextArea("Date")
     @Html.TextArea("MEMO")
     <input type="submit"/>
}

B. the default method attribute of the form output using the Html. BeginForm auxiliary method is POST. If you want to specify it as GET, enter the third parameter, as shown below.


@using(Html.BeginForm("Search","Home",FormMethod.Get))
{
    @Html.TextArea("Keyword")
    <input type="submit" />
}

C. if you want to use HTML forms to upload files, you must add an enctype attribute to the output <form> form tag and set the content to multipart/form-data, as shown below.


@using(Html.BeginForm("Upload","File",FormMethod.Post,new{enctype="multipart/form-data"}))
{
    @Html.TextBox("File1","",new{type="file",size="25"})
    <input type="submit"/>
}

The Html auxiliary method does not have the File method. Therefore, you must use the TextBox method instead, and input the third parameter to replace the built-in type attribute with file.

(2) common form input Elements

Html. BeginForm (), output <form> tag

Html. EndForm (), output </form> tag

Html. Label (), output <label> Label

Html. TextBox (), output <input type = "text"> tag

Html. TextArea (), output <textarea> tag

Html. Password (), output the <input type = "password"> tag

Html. CheckBox (), output <input type = "checkbox"> tag

Html. RadionButton (), output <input type = "radio"> tag

Html. DropDownList (), output the <select> tag.

Html. ListBox (), output <select multiple> tag

Html. Hidden (), output <input type = "hidden"> tag

Html. ValidationSummary (), output error message summary when form verification fails

A. Use of tags

@ Html. Label ("Username", "account") @ Html. TextBox ("Username ")


B. Use of the text box

The reload of Html. TextBox is as follows:

@Html.TextBox("Username") //id, the value of name is Username

@Html.TextBox("Username", "will") //id, the value of name is Username; the value of value is will

@Html.TextBox("Username", "will", new { size=32 })//id, the value of name is Username; html attribute value size=3

If you want to pass Multiple html attribute values and use them in multiple places, follow the example below.


public ActionResult HelperSample1()
        {
            IDictionary<string, object> attr = new Dictionary<string, object>();
            attr.Add("size", "32");
            attr.Add("style", "color:red;");
            ViewData["Dictionary"] = attr;
            return View();
        }
@{
    var htmlAttribute = ViewData["Dictionary"] as IDictionary<string, object>;
}
@Html.TextBox("name","Value",htmlAttribute)<br />
@Html.Password("password","Value",htmlAttribute)<br />
@Html.TextBox("email","Value",htmlAttribute)<br />
@Html.TextBox("tel","Value",htmlAttribute)<br />
@Html.Hidden("id","1")


 
C. Html. DropDownList ()

1) drop-down list of databases not read

public ActionResult HelperSample2 ()
         {
             List <SelectListItem> listItem = new List <SelectListItem> ();
             listItem.Add (new SelectListItem {Text = "Yes", Value = "1"});
             listItem.Add (new SelectListItem {Text = "No", Value = "0"});
             ViewData ["List"] = new SelectList (listItem, "Value", "Text", "");
             return View ();
         }
@ Html.DropDownList ("List", ViewData ["List"] as SelectList, "Please select") // The parameter is the name of the drop-down list, the specified list item, and the value of the default selection item

2) Data from the database drop-down list


Public ActionResult Index()
         {
             Var list = new SelectList(db.Students, "Id", "Age", "3"); //Parameters are data collection, data value, data text, value of selected item
             ViewBag.List = list;
             Return View();
         }
@Html.DropDownList("List")
 

3) data from Enumeration type

ViewBag.Role = new SelectList(Enum.GetValues(typeof(SystemRole)), "");
@Html.DropDownList("Role")

(3) Use a strongly typed auxiliary Method

ASP. net mvc provides a strong type of auxiliary methods from version 2.0 to avoid the problem that data is not displayed or cannot be stored during editing due to incorrect input. In addition, if these strong types of auxiliary methods can be used, the overall development efficiency can be improved.

Basically, the naming method For Strongly-typed auxiliary methods is "add For after the original name", For example, Html. TextBoxFor () or Html. LabelFor (). To use the strongly typed helper method, you must use @ model to define the reference data model of the View page at the top of the View page. If there is no life cycle, the strongly typed helper method cannot be used normally.

Html. LabelFor (), output <label> label, display the field name.

Html. TextBoxFor ()

Html. TextAreaFor ()

Html. PasswordFor ()

Html. CheckBoxFor ()

Html. RadioButtonFor ()

Html. DropDownListFor (), output the <select> tag.

Html. ListBoxFor (), output the <select multiple> tag.

Html. HiddenFor () to generate a hidden field of the HTML form.

Html. DisplayNameFor (): displays the display name of the data model defined in Metadata.

Html. DisplayTextFor (): displays the text of the data model.

Html. ValidationMessageFor (): displays the error message of the data model when the input verification fails.

Html. EditorFor (), used to output the form field editable text box.

In this example, the home page shows the product details. Click the add product link to open the add product page. Enter the information to add the product. The product model class and add product page Code are as follows:

Public class Product
    {
        Public int Id { get; set; }

        [Required]
        [DisplayName("product name")]
        Public string Name { get; set; }

        [MaxLength(200)]
        [DisplayName("Product Description")]
        Public string Description { get; set; }

        [Required]
        Public int UnitPrice { get; set; }
    }
@model MvcApplication1.Models.Product

@using(Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Product Information</legend>

        <div class="editor-lable">
            @Html.LabelFor(model=>model.Name)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model=>model.Name)
            @Html.ValidationMessageFor(model=>model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model=>model.Description)
        </div>
        <div class="editor-label">
            @Html.TextAreaFor(model=>model.Description)
            @Html.ValidationMessageFor(model=>model.Description)
        </div>

        <p>
            <input type="submit" />
        </p>
    </fieldset>
}


3. Use the HTML-assisted method to load the branch view

Previously in ASP. in the development experience of NET Web form, User Control is frequently used, which not only reduces repeated code, but also facilitates page modularization. this easy-to-use concept can also be used in ASP. net mvc, but with a different name, called "partition View )".

(1) What is the division view?

From Partial View literal translation, it is easy to understand that it is a segment View. Therefore, you can use Partial View to wrap part of HTML or display logic to facilitate repeated reference. When you place the created branch View in the View \ Shared directory, any Action or View under the Controller can be loaded. Put the common Parital View in the Views \ Shared directory.

The application scope of the segment view is quite wide. Because it is the HTML display logic of the segment, the overall repeatability is high or a segment of HTML will appear in multiple view pages together, using the segment View for development is a good choice. Based on this advantage, the segment View required by Ajax technology is more suitable for using the segment View.

(2) How to Create a branch view

The process for creating a branch view is the same as that for creating a view. Right-click the/Views/Shared directory of the project, select "add"> "View" from the shortcut menu. Then, select the "Create as branch view" check box.

When using the segment view, you do not need to create the relevant Action because it is only the HTML of the segment and will not call the Action for execution during the call.

(3) Use Html. Partial to load the segment View

The HTML auxiliary method of ASP. net mvc has a special extension method to load the Partial View, called Partial, which allows you to directly retrieve the execution results of the Partial View in the View.

Usage Example
Partial (HtmlHelper, String) Html. Partial ("ajaxPage ")
Partial (HtmlHelper, String, Object) Html. Partial ("ajaxPage", Model)
Partial (HtmlHelper, String, ViewDataDictionary) Html. Partial ("ajaxPage", ViewData ["Model"])
Partial (HtmlHelper, String, Object, ViewDataDictionary) Html. Partial ("ajaxPage", Model, ViewData ["Model"])

 

Because the segment view is fragmented, You must select a complete page to load it.

Example 1: The OnlineUserCounter code of the segment view is as follows.

 

<Span style = "color: red"> online users: 88888 </span>

 

Load the branch view in the Home/Index view.

@Html.Partial("OnlineUserCounter")

 

The preceding method can be used to load the segment view. Because it is a direct load, the called page can be directly called if any data is transmitted.

If multiple segment views are loaded in a view page, you can access the ViewData, TempData, and Model data on the original page in each segment view, this means that these data models passed in from the Controller can be used across various Branch views.

However, when loading the segment view, you can also use Html. the Partial auxiliary method is used to pass in another Model data, so that different Model data can be used in the partition view and when loading the view page, you can also use part of the data on the view page as the data in the branch view page.

Take the Login page of AccountController as an example. When Logon fails, the data entered on the previous page is passed in. When loading another segment view from the view page, you can input an object-type parameter as the model data of the segment view, as shown in the following view page.

@model LoginModel
@{
     ViewBag.Title="Login";
}

@Html.Partila("LoginFail", (object)Model.UserName)

Then, add a branch view named LoginFail under the/Views/Account directory. Its content is as follows:

@ Model System. String the Model data imported from the view page is: @ model

The preceding example shows that the Model in the "Model" and "LoginFail" section view on the general view page is different.

(4) use the Html. Action auxiliary method to load the branch view from the Controller

In addition to loading a view page directly, the branch view page can also be used from the Controller as a general view page. The following OnlineUserCount action is to use the PartialView auxiliary method in the Controller type to load the branch View. The only difference between this loading method and the View auxiliary method is that it does not apply the master page, others are the same.


public ActionResult OnlineUserCount()
{
    return PartialView();
}

Then, you can use Html. Action to load the execution result of this Action on the view page:

@Html.Action("OnlineUserCounter")

The results of loading the Partial view through Html. Action and Html. Partial are the same, but the loading process is quite different. If Html. Partial is used to load the Partial view, the *. cshtml file is directly read through HtmlHelper, and the view is executed and the result is obtained. If Html. action, the IIS will be processed through HtmlHelper again (through Server. execute method), therefore, use Html. action re-executes the Controller lifecycle.

 

Link: https://www.cnblogs.com/yytesting/p/4987633.html

 


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.