ASP. NET MVC programming--model

Source: Internet
Author: User

1 ViewModel

is a special offer to The model used by view uses ViewModel because the entity or domain model contains more or less attributes than the view uses, in which case the entity or domain model does not fit View use.

2 Model Binding

Default Model Binder

through Defaultmodelbinder parses the data from the client and assigns a value to the controller's list of operating parameters.

Show Model Bindings

Use Updatemodel and tryupdatemodel Display the binding model and do not validate unbound fields.

Use when the Updatemodel method binds a model, it throws an exception if the binding fails, and TryUpdateModel does not.

Verify that the model binding succeeds or not

Use Modelstate.isvalid

Get form data

to get form data, use the type The formcollection parameter is used as the operation parameter.

Emptying the model binding state

Use Modelstate.clear (); after the model binding state is emptied, the validation failure information is not displayed on the view, even if the @Html. ValidationSummary () method is used in the view.

Restricting the default binding rules

Use The Bindattribute property modifies the parameter or operation.

 Public classmymodel{ Public stringFiled1 {Set;Get; }  Public stringFiled2 {Set;Get; }} PublicActionResult About ([Bind (Include ="Filed1")]mymodel mm) {//Specific Code} or [Bind (Include="Filed1")] PublicActionResult About (mymodel mm) {//Specific Code}

3 model Retouching

Use some attributes on model properties to achieve the purpose of modifying model properties or validating properties

Attribute name

Describe

Note

Stringlength

Sets the maximum allowable length of a string

Required

Marked fields are required

RegularExpression

The specified regular expression must be met

Range

Specify the range of numbers

CustomValidation

Custom validation Rules

DisplayName

Set the display name of a field

Compare

Compare two fields in a consistent

Can be used to confirm whether the second input matches the first time

MinLength

Sets the minimum length of an array or string

MaxLength

Sets the maximum length of an array or string

Remote

Validate specified fields with controller actions

Public Remoteattribute (String action, string controller);

Cases:

1) Specify the scope of the license

     Public class modelf    {        publicstringgetset;}        [Range (typeof"1/1/2018""1/1/2019"  )]        publicgetset;}    }

2) using placeholders

[Stringlength{0} must contain a minimum of {2} characters.  "6)]publicstringgetset;}

4 extensions

Custom annotations

Create custom attributes that inherit from Validationattribute,validationattribute has two virtual methods that can be overloaded with these two virtual methods to complete the custom validation logic.

Public virtual bool IsValid (object value);

Protected virtual Validationresult IsValid (object value, Validationcontext validationcontext);

Cases:

     Public classCustomvalidationattribute:validationattribute { PublicCustomvalidationattribute ():Base("{0} reason for validation failure")        { }        protected OverrideValidationresult IsValid (Objectvalue, Validationcontext validationcontext) {            if(Value! =NULL)            {                //Validation Logic//validation failed with error message returned                stringErrorMessage =formaterrormessage (validationcontext.displayname); return NewValidationresult (errormessage); }            returnvalidationresult.success; }    }

5 principle

the data for the incoming operation exists in the the request URLfor the HTTP request, the message header, and the message body. When an operation has parameters,the MVC framework uses the model binder (default or custom) to look up data in an Http request to build a list of parameters for the controller operation.

The time the validation occurred

Model validation is done before the operation executes. When the model binder updates the model properties with the new values, the model validator is obtained with the current model metadata, the Model verifier finds all the attributes that are applied to the model properties and executes the validation logic, and the model binder captures all failed validation rules and puts them into the model state.

Model State

The model state contains the values that were bound during model binding, and any errors that occurred during model binding.

Reference:

1.Jess chadwick/todd Snyder/hrusikesh Panda, Xu Lei/Xu Yang

Translated. ASP. NET MVC4 Web programming

2.Jon Galloway/phil Haack/brad wilson/k Scott Allen, Sun/Shang translate ASP. NET MVC4 Advanced Programming (Fourth Edition)

3. Huangpao, ASP. MVC4 Development Guide

4. Jing Jinnan, ASP. NET MVC4 Framework

5.https://www.asp.net/mvc

-----------------------------------------------------------------------------------------

Reprint and quote please specify the source.

Time haste, the level is limited, if has the improper place, welcome correction.

ASP. NET MVC programming--model

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.