ASP. net mvc: knowledge points (2) and mvc knowledge

Source: Internet
Author: User

ASP. net mvc: knowledge points (2) and mvc knowledge

1. implement Controller dependency injection:

1. Customize the Controller factory class that inherits the DefaultControllerFactory class and override the GetControllerInstance method. (For example, InjectControllerFactory)

2. register the Controller factory class in the Application_Start method in the Global. asax file, for example:

ControllerBuilder.Current.SetControllerFactory(new InjectControllerFactory());

2. Add the ActionName feature to the Action Method to specify its alias, or add a NonAction to indicate that the method will not be matched by the route, you can inherit the ActionMethodSelectorAttribute abstract class and override the IsValidForRequest method to implement Custom Action Method selectors, such as HttpGet, HttpPost, HttpPut, HttpDelete, and NonAction.

3. Step Controller: Inherit from the AsyncController abstract class and customize the asynchronous Action method (there are two asynchronous Methods: XxxAsync/XxxCompleted and Task return values). For details, see ASP. net mvc asynchronous Action definition and execution Principle

4. The basic filter is as follows. You can customize the filter through the corresponding interface.

5. dynamically add or process content on the View

1. Inline code (code snippet): for example, @ {...} or <%... %>
2. Html helper method: generate one or more HTML elements, such as Html. Label and Html. Editor.
3. Section: Insert a part of the created content (like ASP. NET PlaceHolder) at the specified position, for example, @ section sectionName {...}
4. Partial view: it exists in a single view file and can be shared as sub-content in multiple views, such as Html. Partial, Html. RenderPartial
5. Child action, which is equivalent to a UI component that contains the business logic. When using child action, it calls the action in controller to return a view and inserts the result into the output stream, such as Html. Action, Html. RenderAction

6. HTML Helper Extension Method: HTML elements can be directly generated, mainly divided into the following types:

1. Link class: Contains extension methods for generating various links in the System. Web. Mvc. Html. LinkExtensions static class;
2. Form class: the static class System. Web. Mvc. Html. FormExtensions contains the extension method for generating the From element;
3. input class: The System. Web. Mvc. Html. InputExtensions static class contains extension methods for generating various input elements;
4. Multi-text input class: The System. Web. Mvc. Html. TextAreaExtensions static class contains the extension method for generating TextArea elements;
5. Select class: The System. Web. Mvc. Html. SelectExtensions static class contains the extension method for generating various selection elements;
6. Dynamic editor template class: the static class System. Web. Mvc. Html. EditorExtensions contains methods for dynamically generating form member elements based on the type to be specified;

To customize the HTML Helper dynamic editor template class, you can create a local view file in the/Views/Shared/EditorTemplates folder according to the MVC conventions. The sample code is as follows:

// Define the html helper template method: @ model MvcApplication1.Models.Role@Html.DropDownListFor (m => m, new SelectList (Enum. getNames (Model. getType (), Model. toString () // use in View: @ model MvcApplication1.Models.User@Html.EditorFor (m => m. role)

Note: The template class file name must be the same as the member type name, or specify the type of Custom template used by the member in the data entity class (for example, [UIHint ("Role")]).

7. Use AJAX in the MVC View:

1. Use native Ajax or third-party class libraries (such as jQuery. ajax)

2. Use MVC Unobtrusive Ajax

A. Configure to start Unobtrusive Ajax in the Web. config file (enabled by default)

    <appSettings>         <add key="UnobtrusiveJavaScriptEnabled" value="true" />     </appSettings> 

B. Introduce the corresponding JS script file at the top of the called page, as shown below:

    <script src="~/Scripts/jquery-1.8.2.min.js"></script>    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

C. Use Ajax. BeginForm to wrap form members and set parameters for Ajax. BeginForm.

The sample code is as follows:

ACTION Code:

        public ActionResult Ajax()        {            return View();        }        public ActionResult GetPersons(string selectedRole)        {            IEnumerable<Person> persons = new[]{new Person(){FirstName="z", LastName="x",Role=Role.User},            new Person(){FirstName="z1", LastName="x",Role=Role.Admin},            new Person(){FirstName="z2", LastName="x",Role=Role.User},            new Person(){FirstName="z3", LastName="x",Role=Role.Admin},            new Person(){FirstName="z4", LastName="x",Role=Role.User}};            if (selectedRole != "All")            {                persons = persons.Where(p => Enum.GetName(typeof(Role), p.Role) == selectedRole);            }            return PartialView(persons);        }

VIEW code:

// Main view Ajax 

 

8. Model Binding): A bridge between an HTTP request and an Action method. It creates a. NET object based on the Model type in the Action method and assigns the HTTP request data to the object after conversion.

A. Model Binder (Model Binder), as its name implies, can be interpreted as A tool for binding data to A Model.

The default Model Binder built in the MVC Framework is the DefaultModelBinder class. When Action Invoker does not find the custom Binder, defamodelmodelbinder is used by default. By default, defamodelmodelbinder finds the value to be bound to the Model in the following four ways:

The value provided by the Request. Form and HTML form elements.
RouteData. Values, the value provided by the application route.
Request. QueryString, the query string value of the requested URL.
Request. Files: Files uploaded by the client.

B. bind to a composite type (nested join type, Indexable type, etc.). Note that the element name of the form member in the view must comply with the join and Indexable attributes, as shown in the following example:

// MODELpublic class Person {public int PersonId {get; set;} public string FirstName {get; set;} public string LastName {get; set;} public Address HomeAddress {get; set ;}} public class Address {public string City {get; set ;}public string Country {get; set ;}// VIEW@Html.EditorFor (m => m. homeAddress. country) // or <input id = "HomeAddress_Country" name = "HomeAddress. country "type =" text "value =" "/>
// Write @ Html in VIEW for the index type. editor ("[" + I + "]. country ") // or @ Html. editorFor (m => m [I]. country) // or <input name = "[0]. country "type =" text "value =" "/>

Of course, you can implement the ModelBinder class yourself if you don't want to be so troublesome, and explicitly specify ModelBinder in the action method, as shown below:

        public ActionResult Index([ModelBinder(typeof(CustomerModelBinder))]Person p)        {            return View();        }

IX. Methods for Model Verification:

1. Use ModelState in the Action method to determine the validity of the attribute values of the Model object. For example:

Public ActionResult UpdatePerson (Person p) {if (string. IsNullOrEmpty (p. FirstName) {ModelState. AddModelError ("FirstName", "FirstName is not allow null! ");} If (string. IsNullOrEmpty (p. LastName) {ModelState. AddModelError (" LastName "," LastName is not allow null! ");} If (ModelState. IsValid) {// execute update} return View ();}

2. Define verification rules on the attributes of the Model. Then, the defamodelmodelbinder class automatically performs verification, for example:

Public class Person {[Range (1, int. maxValue)] public int PersonId {get; set;} [Required (ErrorMessage = "Enter the last name")] public string FirstName {get; set ;} [Required (ErrorMessage = "Enter name")] public string LastName {get; set;} [Required (ErrorMessage = "Enter the Address completely")] public Address HomeAddress {get; set ;}public Role {get; set ;}}

3. inherit the ValidationAttribute abstract class and override the IsValid method to customize the verification feature class (example below), and then use the same method as method 2

Public class MailAttribute: ValidationAttribute {public override bool IsValid (object value) {if (value = null) return false; var regex = new System. text. regularExpressions. regex (@ "^ [a-zA-Z0-9 _-] + @ [a-zA-Z0-9 _-] + (\. [a-zA-Z0-9 _-] +) + $ ", System. text. regularExpressions. regexOptions. ignoreCase); return regex. isMatch (value. toString () ;}// set a property of the MODEL: [Mail (ErrorMessage = "invalid EMail address")] public string EMail {get; set ;}

4. MODEL self-verification: Let the MODEL class implement the IValidatableObject interface, verify and judge in the Validate method, and then the DefaultModelBinder class will automatically perform verification, such:

    public class Computer:IValidatableObject    {        public string CPU { get; set; }        public string MB { get; set; }        public string MEM { get; set; }        public string HDD { get; set; }        public string Power { get; set; }        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)        {            var errors=new List<ValidationResult>();            if (string.IsNullOrEmpty(CPU))            {                errors.Add(new ValidationResult("CPU is not allow null!"));            }            if (string.IsNullOrEmpty(MB))            {                errors.Add(new ValidationResult("MB is not allow null!"));            }            if (string.IsNullOrEmpty(MEM))            {                errors.Add(new ValidationResult("MEM is not allow null!"));            }            if (string.IsNullOrEmpty(Power))            {                errors.Add(new ValidationResult("Power is not allow null!"));            }            return errors;        }    }

By default, the above verification is performed after submission to the server. You can also enable client verification or remote verification (The implementation principle is based on AJAX), which is not described here.

 

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.