Asp. Net MVC4 series-advanced Article Helper (2)

Source: Internet
Author: User

This chapter introduces Helper in Asp. NetMVC4.

First of all, prepare for the work. To make it easier for readers to read, I will. net MVC4 series-the Code of Helper (1) in the advanced article is copied here. This article begins with this:

Person class (in Model ):


  public class Person    {        public int PersonId { get; set; }        public string FirstName { get; set; }        public string LastName { get; set; }        public DateTime BirthDate { get; set; }        public Address HomeAddress { get; set; }        public bool IsApproved { get; set; }        public Role Role { get; set; }    }


    public class Address    {        public string Line1 { get; set; }        public string Line2 { get; set; }        public string City { get; set; }        public string PostalCode { get; set; }        public string Country { get; set; }    }    public  enum Role    {        Admin,        User,        Guest}


PersonController. cs

   public class PersonController : Controller   {        public ActionResult CreatePerson()        {            return View(new Person());        }         [HttpPost]        public ActionResult CreatePerson(Person person)        {            return View(person);        }   }


Route:

     routes.MapRoute(name: "FormRoute",url:"app/forms/{controller}/{action}");        }

View (CreatePerson. cshtml)


@modelMVCHelperStudy.Models.Person@{   ViewBag.Title = "CreatePerson"; }CreatePerson    @using(Html.BeginRouteForm("FormRoute", new {},FormMethod.Post,new { @class ="personClass", data_formType="person"})) {PersonId@Html.TextBoxFor(m =>m.PersonId)FirstName@Html.TextBoxFor(m => m.FirstName)LastName@Html.TextBoxFor(m =>m.LastName)Role@Html.DropDownListFor(m =>m.Role,new SelectList(Enum.GetNames(typeof(MVCHelperStudy.Models.Role))))} 


Test run:


First, use the template method to reconstruct the View

Replace the form intermediate code:

PersonId@Html.Editor("PersonId")FirstName@Html.Editor("FirstName")LastName@Html.EditorFor(m =>m.LastName)Role@Html.EditorFor(m => m.Role)BirthDate@Html.EditorFor(m =>m.BirthDate)


Code Description: Html. Editor is used to replace the previous implementation.

Take a look at the generated html

 


Compared with the previously generated html, the difference is that the "type" attribute is added, and the advantage is that it makes html5 display different based on different types. This requires support for html5 browsers.

Common MVC template helper Method

Html. Display ("name ")

Html. DisplayFor (m => m. name)

Html. Editor ("name ")

Html. EditorFor (m => m. name)

Html. Label ("name ")

Html. LabelFor (m => m. name)

Label Method and Display Method

Adjust the Controller code:

  public ActionResult CreatePerson()        {             return View(newPerson()                {                   FirstName = "iori",                   LastName = "l",                   PersonId = 100,                   BirthDate = DateTime.Now.AddYears(-20)                });        }


Returns a default Person.

Adjust the View code:

@Html.Label("PersonId")@Html.Display("PersonId")@Html.Label("FirstName")@Html.Display("FirstName")@Html.LabelFor(m => m.LastName)@Html.DisplayFor(m => m.LastName)@Html.LabelFor(m => m.Role)@Html.DisplayFor(m => m.Role)@Html.LabelFor(m => m.BirthDate)@Html.DisplayFor(m => m.BirthDate)


In order to compare the Display and Label, it is displayed separately. Test results:


As you can see, the Display displays the PrZ labels? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> Principal + ExhYmVsysfP1Mq + Principal + CjxwPtTZttSxyNK7z8LJ + rPJtcRodG1so7o8L3A + Principal" brush: java; ">

As you can see, the label automatically generates the for attribute, while the display directly places the value on the page, even without any conver labels.

Whole-Model Template

Whole-Model Template mainly includes:

Html. DisplayForModel ()

Generate html (read-only) based on the type of each property of the current model)

Html. EditForModel ()

Generate editable html based on the type of each property of the current model

Html. LabelForModel ()

Generate tags based on the current model

Use Html. EditForModel to reconstruct the View code:

@using(Html.BeginRouteForm("FormRoute", new {},FormMethod.Post,new { @class = "personClass",data_formType="person"})) {@Html.EditorForModel()}


Run and view results


Use model metadata

1. hiddenInput

Add an attribute to the PersonId:

[HiddenInput (DisplayValue = false)]

Run and test:


Click submit

Debug to view the value of Person. You can see that the PersonId has been submitted and the value is 100. The reason is that our attribute tells mvcframework to parse the input to Hidden and view the html:

 


We can see that the type has been resolved to hidden.

Use the [ScaffoldColumn] attribute

Not every field in a class needs to be resolved to html by mvc frame. If you want to skip a property, you can use this property. For example:

[ScaffoldColumn(false)]public int PersonId { get; set; }


In this case, PersonId will not be involved in the process from property parsing to html.

Use [Display (Name = "XXX")]

If you want the Label parsed by html to be displayed as another word, you can use this attribute. For example:

[Display(Name = "Birth Date")]public DateTime BirthDate { get; set; }


Corresponding html Tag:

BirthDate


Use [DataType (type)]

If you want to change the type of mvc frame Parsing, you can use this attribute, for example:

[DataType(DataType.Date)]public DateTime BirthDate { get; set; }


In this way, mvc parses this property as the Date type, instead of DateTime.

Corresponding html tags:

 


Types available for other DataType

DateTime

Date

Time

Text

PhoneNumber

MultipleText

Password

Url

EmailAddress

Use the [UIHint ("XX")] attribute

The UIHint attribute allows you to specify a Template Name. When the mvc framework parses this attribute, the corresponding template is first found and then parsed to the corresponding html. For example:


[UIHint("MultilineText")] public  string FirstName { get; set; }



Corresponding html:

iori


Built-in MVC Template

Boolean

DateTime

Date

EmailAddress

HiddenInput

Html

MultiLineText

Number

Object

Password

String

Time

Text

Tel

Url

Mvc generates corresponding html for each template. You can try it one by one and apply it to the project as needed. Each template can also be rewritten.

Use metadata class

1. Modify the Person class to partial and remove all DataType and Hint (like an Entity class ):


  public int PersonId{ get; set; }        public string FirstName { get; set; }        public string LastName { get; set; }        public DateTime BirthDate { get; set; }        public Address HomeAddress { get; set; }        public bool IsApproved { get; set; }        public Role Role { get; set; }


To apply the metadata type to the Person class, you must set it to partial first.

2. Create a metadata class

public partial class PersonMetaData {[HiddenInput(DisplayValue=false)]public int PersonId { get; set; }[Display(Name="First")]public string FirstName { get; set; }[Display(Name = "Last")]public string LastName { get; set; }}


3. Add the metadatatype attribute to the Person class.

[MetadataType (typeof (PersonMetaData)]

4. Use EditFormModel in View

@using(Html.BeginRouteForm("FormRoute",new {}, FormMethod.Post,new { @class = "personClass",data_formType="person"})) {   @Html.EditorForModel()}


The purpose of using the metadata class is to separate the Entity class from the class marked by the MVC Attribute. However, when displaying the object, MVCFramework needs to find the consistent Property from the medadata class and apply the Attribute. Run, view results,


You can see that the tag name has changed and the PersonId is Hidden. Therefore, both the Display tag and the Hidden tag of the Metadata class have an effect.

Resolution nesting type: Address

In the previous example, because the HomeAddress field is class, MVCFramework does not recognize it. Therefore, you need to manually call EditFor:

  

@Html.EditorFor(m => m.HomeAddress)



Run:


We can see that the Address type can be identified.

Display the specified Template

Html. EditorFor (m => m. SomeProperty, "MyTemplate ")

You can tell the MVC Framework to use the specified Template.

Search Order of Template

1. template of Customize

2. template of Built-in

3. input the Template of Helper, e.g.: Html. EditorFor (m => m. name, "T ");

4. UIHint

5. DataType

Customize a Template

Create an EditorTemplates folder in the Shared folder. MVCFramework will find all the template Mize templates.

Create a View and put it in the EditorTemplates folder. Each member of the enumeration can be reflected and displayed:

@model Enum@Html.DropDownListFor(m => m,Enum.GetValues(Model.GetType()).Cast
 
  ().Select(m => {string enumVal =Enum.GetName(Model.GetType(), m);return new SelectListItem() {Selected = (Model.ToString() ==enumVal),Text = enumVal,Value = enumVal};}))
 


Application: Add a UIHint to the Role Member in the metadata class.

[UIHint("Enum")]public Role Role { get; set; }


Run and view results


You can see that the custom Template is successfully working.

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.