Chapter 1 model verification and Chapter 4 Model

Source: Internet
Author: User

Chapter 1 model verification and Chapter 4 Model

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

Note: 1.In web. config, add <globalization culture = "en-US" uiCulture = "en-US"> to the system. web element to change the region File Settings.

2.The DataType annotation attribute cannot be used to verify user input, but can only be used to render prompts using template guides.

  3.Implements the IValidatableObject Interface Verification Model class. Client verification is not supported.

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

Model Verification(Model Validation): Make sure that the data received by the user is suitable for binding to the Model. If not, provide feedback to the user to help modify the problem.

Process:

1.Check received dataTo maintain the integrity of the domain model. By rejecting meaningless data in the domain environment, you can prevent strange situations in applications.

2.Help Users correct problemsTo provide users with the information and tools they need to follow and interact with the application.

1. Clearly verify the model:

  1. Set the checkbox style:

In ~ In/Views/Shared/EditorTemplates/Boolean. cshtml:

@model bool?@if (ViewData.ModelMetadata.IsNullableValueType){    @Html.DropDownListFor(m => m, new SelectList(new[] {"Not Set", "True", "False"}, Model))}else{    ModelState state = ViewData.ModelState[ViewData.ModelMetadata.PropertyName];    bool value = Model ?? false;    if (state != null && state.Errors.Count > 0)    {        <div class="input-validation-error" style="float: left">            @Html.CheckBox("",value)        </div>    }    else    {        @Html.CheckBox("",value)    }}

2. display the verification message:

@ Model ModelValidation. Models. Appointment @ {ViewBag. Title = "Make A Booking";} @ Html. ValidationSummary ()<P> name: @ Html. editorFor (m => m. clientName) </p> <p> reservation Date: @ Html. editorFor (m => m. date) </p> <p> @ Html. editorFor (m => m. termAccepted) Terms of the receiving Agreement </p> <input type = "submit" value = "Reservation"/>}

Useful ValidationSummary helper overload method

Overload Method Description
Html. ValidationSummary () Generate summary of all verification errors
Html. ValidationSummary (bool) True: only model-level errors are displayed. Default Value: false. All errors are displayed.
Html. ValidationSummary (string) Add a message (string) before all verification error summaries)
Html. ValidationSummary (bool, string) Add a message (string) true before all verification error summaries: only model-level errors are displayed.

Display Attribute-level verification message:

@ Model ModelValidation. models. appointment @ {ViewBag. title = "Make A Booking";} 

 2. verification is performed in the default model binder.

DefaultModelBinder

Method Description Default implementation
OnModelUpdated Called when the binder tries to assign values to all attributes of the model object Use verification rules defined by model metadata and register errors with ModelState.
SetProperty Called when the binder uses a value for a specific attribute

If this attribute cannot save Null values and there is no available value,

An error message "The <name> fieldis required" will be registered with ModelState;

If there is a value but it cannot be parsed, "The value <value> is not validfor <name>" will be registered"

1. Use metadata to specify verification rules:

Public class Appointment //: IValidatableObject {[DisplayName ("customer name")] [Required] public string ClientName {get; set;} [DataType (DataType. date)] [DisplayName ("Date")] [Required (ErrorMessage = "Enter time")] public DateTime Date {get; set ;} [DisplayName ("terms of acceptance")] [Range (typeof (bool), "true", "true", ErrorMessage = "must accept the terms of the Agreement")] public bool TermAccepted {get; set ;}

Built-in verification annotation attributes

Annotation attributes Example Description
Compare [Compare ("MyOtherProperty)] The two attributes must have the same value. This is useful when you are required to provide two identical values for a property.
Range [Range (10, 20)] A numeric value (attribute type that implements IComparable). value Range: [Range (int. MinValue, 50)]
RegularExpression [RegularExpression ("pattern")] A string value that must match the regular expression pattern. All values, not substrings. Case Insensitive: [RegularExpression ("(? I) mypattern ")]
Required [Required] Non-null value. Acceptable space: [Required (AllowEmptyStrings = true)]
StringLength [StringLength (10)] Maximum length of a string value. Minimum Length: [StringLength (10, MinimumLength = 2)]

III,Client Verification

Enabled: 1. <ettings> in web. config

<Add key = "ClientValidationEnabled" value = "true"/>
<Add key = "UnobtrusiveJavaScriptEnabled" value = "true"/>

2. Reference three JS libraries:

     Jquery

Jquery. Validate

Jquery. validate. unobtrusive

4. remote verification: The JosnResult type is required. Receive a string parameter and perform type conversion, parsing, or explicit model binding.

1. Action method: 

Public JsonResult ValidateDate (string date) {DateTime parseDate; if (! DateTime. tryParse (date, out parseDate) {return Json ("enter a date in the format of" mm/dd/yyyy ", JsonRequestBehavior. allowGet);} else if (DateTime. now> parseDate) {return Json ("enter a future time for Reservation", JsonRequestBehavior. allowGet);} else {return Json (true, JsonRequestBehavior. allowGet );}}

2.Remote annotation attributes:

        [Remote("ValidateDate","Home")]         public DateTime Date { get; set; }

Source code: http://yunpan.cn/ccGAZD7d5QL6Z access password 672a

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.