MVC5 + EF6 + Bootstrap3 (9) HtmlHelper usage Daquan (bottom)

Source: Internet
Author: User

Original: MVC5 + EF6 + Bootstrap3 (9) HtmlHelper usage Daquan (bottom)

Article Source: slark.net-Blog Park http://www.cnblogs.com/slark/p/mvc5-ef6-bs3-get-started-httphelper-part2.html

Previous section: MVC5 + EF6 + Bootstrap3 (8) HtmlHelper usage Daquan (top)

Next section: MVC5 + EF6 + BOOTSTRAP3 (10) Data query page

SOURCE download: Click I download

Directory:
    • Description
    • Form form
    • Create a custom label using Tagbuilder
    • Strongly typed HtmlHelper
    • Labelfor Data Labels
    • Displayfor and editorfor displaying and editing model data
    • Study Questions
Description

This section continues with the previous section MVC5 + EF6 + Bootstrap3 (8) HtmlHelper usage Daquan (above), continuing to discuss the use of HtmlHelper.

All the following htmlhelper codes are written in the defaultaction.cshtml file in the Defaultcontroller folder under the Views folder. This view file corresponds to a controller named Defaultcontroller.

Form form

Generating a form form in HtmlHelper uses two functions: BeginForm and EndForm. There are two ways to generate a <form>...</form> form, using the following method:

@using (Html.BeginForm ("ActionName","controllername", Formmethod.get)) {@Html. TextBox ("NameId")    <input type="Submit"Value="Submitbutton"/>}@{html.beginform ("ActionName","controllername", formmethod.post);} @Html. TextBox ("NameId")    <input type="Submit"Value="Submitbutton"/>@{html.endform ();}

We have written a TextBox and a Submit button in the form. The HtmlHelper usage of the TextBox is already mentioned in the previous section, and the more peculiar is that the submit button does not have a corresponding htmlhelper function to generate, and it needs to be written directly in the HTML language. We'll solve the problem later.

Look closely at the difference between the two methods of generating form: The first method puts the Html.BeginForm () function into the @using () {} structure, which can directly generate the start and end tags of the form; the second method writes Html.BeginForm () The function generates a start tag, and then the last write Html.endform () function generates the end tag. These two methods produce the same result. The results are as follows:

<formAction= "/controllername/actionname"Method= "Get">
<inputID= "NameId"name= "NameId"type= "text"value="" />
<inputtype= "Submit"value= "Submitbutton" /></form>
<formAction= "/controllername/actionname"Method= "POST"><inputID= "NameId"name= "NameId"type= "text"value="" />    <inputtype= "Submit"value= "Submitbutton" /></form>

You can see from the running result that the first parameter of BeginForm () specifies the name of the action, the second parameter specifies the name of the controller, and the third parameter specifies whether the post method or the Get method is used when committing. The first form in the code above uses the Get method, and the second form uses the Post method.

Create a custom label using Tagbuilder

Before we say that there is no htmlhelper function for the submit button, we create one ourselves.

God closes a door, it will open a window for us. This window is tagbuilder. As the name implies, Tagbuilder is the tag builder, and we use it to build our own tag generation function.

First create a Classes folder in your project to hold the class that we are going to create. Create a class named HtmlExtensions.cs in this folder, this class name is not mandatory and can be written. In this class, write the following code:

usingSYSTEM.WEB.MVC; Public Static classhtmlextensions{/// <summary>    ///Customize a @html. Submit ()/// </summary>    /// <param name= "helper" ></param>    /// <param name= "value" >Value Property</param>    /// <returns></returns>     Public StaticMvchtmlstring Submit ( ThisHtmlHelper Helper,stringvalue) {        varBuilder =NewTagbuilder ("input"); Builder. Mergeattribute ("type","Submit"); Builder. Mergeattribute ("value", value); Builder.        ToString (tagrendermode.selfclosing); returnmvchtmlstring.create (builder.    ToString ()); }}

Let's take a look at the code above:

    • First of all, to use Tagbuilder will introduce SYSTEM.WEB.MVC class library.
    • Then we look at the parameters of this function, this HtmlHelper helper guarantees that this method will be added to the HtmlHelper, and string value corresponds to the text displayed by the future Commit button, which is the Value property.
    • var builder = new Tagbuilder ("input"), which sets the name of the tag we created as input.
    • The Mergeattribute function adds attributes to the created element, such as Mergeattribute ("type", "submit"), which is added to the type= "submit" attribute.
    • Tagrendermode.selfclosing makes the generated label self-closing, which means there is <input/> this form.
    • Finally, Mvchtmlstring is used as the return value so that the return value is not escaped, such as "<" will not be converted to "&lt". That's what we don't want to see.

We then write the following code in the view to call the function we just wrote:

@Html. Submit ("submitbutton")

The resulting results are as follows:

<type= "Submit"  value/>

You can see that the tag names, attributes, and self-inclusions that we set in the function are all done. This allows us to successfully generate a self-created submit button.

Strongly typed HtmlHelper

HtmlHelper have strong and weak types. All of the functions described earlier are weakly typed. What is the difference between strong and weak types? The simple point is that the strong type uses the model in MVC, and the weak type does not.

Almost every weakly typed function in the HtmlHelper corresponds to a strongly typed function whose corresponding relationship is that the strongly typed function name has a more for than the weak type. For example, a TextBox () is a weakly typed function, so its corresponding strongly typed function is Textboxfor ().

In the latter part we need to use model to show the code, so creating a simple model in the Models folder in the solution is called the Simplicity class. The file name is Simple.cs code as follows:

namespace slarkinc.models{    publicclass (Simple)     {        public  Get Set ; }    }}

Since it's a simple model, we'll just give it a property: Name.

After creating this model we can initialize and assign the model to the controller and pass it to view to prepare for our strongly typed HtmlHelper. Edit the DefaultControllerController.cs file and write the following code:

usingSYSTEM.WEB.MVC;usingSlarkinc.models;namespaceslarkinc.controllers{ Public classDefaultcontrollercontroller:controller {//GET:/defaultcontroller/         PublicActionResult DefaultAction () {simple s = new Simple  (); s.name             = "Slark"; return View (s); }    }}

The yellow part of the figure initializes the model, assigns a value to the model, and passes the model to view.

Below we will show the data in the model using the strongly typed htmlhelper in the view. As you can see from the above code, Defaultcontroller calls the view named DefaultAction. So we found the Defaultcontroller folder under the Views folder and edited the DefaultAction.cs file. Add the following code to the first line of the file:

@model SlarkInc.Models.Simple

This line of code indicates that this view uses the simple model.

Then insert the following code into the file:

@Html. Textboxfor (M =>m.name)

This is an example of our strongly typed HtmlHelper function textboxfor. This function has only one parameter M =>m.name. The m here can be replaced by other names, which refer to our model. The meaning of this parameter of Textboxfor is to take the model's Name property. Since we initialized this value in the controller, this value should be "Slark". The results of the operation are as follows.

<id= " name" name= "name"  type= "text"  Value= "Slark"/>

As can be seen from the above results, the name of the property is assigned to the ID and name of the element, and the attribute value Slark is assigned to the Value property. This allows us to complete a simple strongly typed htmlhelper.

Labelfor Data Labels

One of the great benefits of a strong type is that we can change the model to show the model in all of the view. As an input box:

How can you change the text in front of the input box by changing the model? We're going to use dataannotations here, someone calls it metadata, or it's called data annotations. Simply put, it is a description of the data. After that, you can read this information and display it with HtmlHelper labelfor. We write the simple class as follows:

 using  System.ComponentModel.DataAnnotations; namespaceslarkinc.models{ Public classSimple { [Display (Name = "Name" )]
Public stringName {Get;Set; } [Display (Name = "e-mail" )]
     Public string Email { get; Set ; } }}

The yellow part of the code is the code we add to the use of metadata. The first line of the section introduces the class libraries that are required to use the metadata. [Display (Name = "e-mail")] This line indicates that we display the string "E-mail" when we want to display the name of the variable. The HtmlHelper function labelfor () is where you get the string that needs to be displayed.

In Defaultcontroller we will assign a value to the email variable, the code is as follows:

Using system.web.mvc;using slarkinc.models;namespace slarkinc.controllers{public    class Defaultcontrollercontroller:controller    {        //GET:/defaultcontroller/public        ActionResult DefaultAction ()        {simple            s = new Simple ();            S.name = "Slark";            S.email = "[Email protected]";            return View (s);}}    

Write the following code in the corresponding view:

@Html. labelfor (m =  m.email)= m.email)

The Labelfor function obtained by the yellow flag is a simple class email attribute, and the Labelfor function will look for the display metadata for the properties of the corresponding email in the model, resulting in the following results:

<for= "Email">e-mail</label>  <ID= "email " name= "email " type  = "text"  value= "[email protected]"/>

Look at the resulting results the LABELFOR function generates a <Label> tag, and its property for value corresponds to the variable name "email", and the label's internal text innertext is the value "e-mail" of the display metadata's Name property.

Displayfor and editorfor displaying and editing model data

One of the most important applications of metadata in ASP. NET MVC is the model that controls the type of HTML elements that are generated when the data is displayed and modified. Displayfor is used to display data in HtmlHelper, and editorfor is used to edit the data. They all generate different types of HTML elements based on the metadata's description of the data.

Change simple to the following code:

usingSystem.ComponentModel.DataAnnotations;namespaceslarkinc.models{ Public classSimple {[Display (Name="Name")]                Public stringName {Get;Set; } [Display (Name="e-Mail")] [DataType (datatype.emailaddress)]       
Public stringEmail {Get;Set; } }}

The yellow part of the code is a description of the email data type. Its data type is the e-mail address EmailAddress. Write the following code in the view:

= M.email)

Both Displayfor and editorfor use the model's email attributes as their own parameters. The results of the operation are as follows:

The corresponding code is as follows:

 <  a  href  = "mailto:[email protected]"  >  [Email protected] </ a  >  <  input  class  = "Text-box single-line"   ID  = "Email"   name  = "Email"   type  = "Email"   = "[email protected]"  />  

From the results you can see that because the data type is emailaddress, it generates a hyperlink to send a message when the data is displayed. An email-only input box is generated when you edit the data <input type= "email" >.

Study Questions

Learning without thinking is not the case, but thinking without learning is dangerous. Here are a few study questions for everyone to test the learning effect.

There are several ways to generate a form in 1.HtmlHelper. How to write separately?

2. How to customize a htmlhelper function that can generate elements.

What are the similarities and differences between 3.LableFor, displayfor and editorfor function usage?

This concludes this article. HtmlHelper contains more things, there are some things not introduced, if you are interested I can continue to expand. Welcome to the discussion. If you like, recommend it!

Previous section: MVC5 + EF6 + Bootstrap3 (8) HtmlHelper usage Daquan (top)

Next section: MVC5 + EF6 + BOOTSTRAP3 (10) Data query page

Slark.net

Source: http://www.cnblogs.com/slark/

This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility. If you have any questions or suggestions, please enlighten me, thank you very much.

MVC5 + EF6 + Bootstrap3 (9) HtmlHelper usage Daquan (bottom)

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.