1. Simple Verification
In ASP. in Net MVC, the verification is at the Controller layer, while the error is displayed at the View layer. The Controller layer verifies the error through the ModelState attribute, and the ModelState state is passed AddModelError () method.
In the View layer, Html-assisted methods are used for rendering. The two methods are:
Html. ValidationMessage ()
Html. ValidationSummary ()
Simple Controller layer Verification
[AcceptVerbs (HttpVerbs. Post)]
Public ActionResult Create ([Bind (Exclude = "CustomerId")] Customer customer)
{
If (customer. CompanyName. Length = 0)
{
ModelState. AddModelError ("CompanyName", "CompanyName cannot be blank ");
}
If (customer. EmailAddress. Length = 0)
{
ModelState. AddModelError ("EmailAddress", "EmailAddress cannot be blank ");
}
If (! ModelState. IsValid)
{
Return View ();
}
Try
{
_ Entities. AddToCustomer (customer );
_ Entities. SaveChanges ();
Return RedirectToAction ("Index ");
}
Catch
{
Return View ();
}
}
Html helper methods at the View layer: Html. ValidationMessage () and Html. ValidationSummary ()
<% @ Page Title = "" Language = "C #" MasterPageFile = "~ /Views/Shared/Site. Master "Inherits =" System. Web. Mvc. ViewPage <MvcApplication4.Models. Customer> "%>
<Asp: Content ID = "Content1" ContentPlaceHolderID = "TitleContent" runat = "server">
Create
</Asp: Content>
<Asp: Content ID = "Content2" ContentPlaceHolderID = "MainContent" runat = "server">
<H2> Create
<% = Html. ValidationSummary ("Create was unsuccessful. Please correct the errors and try again.") %>
<% Using (Html. BeginForm () {%>
<Fieldset>
<Legend> Fields </legend>
<P>
<Label for = "NameStyle"> NameStyle: </label>
<% = Html. TextBox ("NameStyle") %>
<% = Html. ValidationMessage ("NameStyle", "*") %>
</P>
<P>
<Label for = "Title"> Title: </label>
<% = Html. TextBox ("Title") %>
<% = Html. ValidationMessage ("Title", "*") %>
</P>
<P>
<Label for = "FirstName"> FirstName: </label>
<% = Html. TextBox ("FirstName") %>
<% = Html. ValidationMessage ("FirstName", "*") %>
</P>
<P>
<Label for = "MiddleName"> MiddleName: </label>
<% = Html. TextBox ("MiddleName") %>
<% = Html. ValidationMessage ("MiddleName", "*") %>
</P>
<P>
<Label for = "LastName"> LastName: </label>
<% = Html. TextBox ("LastName") %>
<% = Html. ValidationMessage ("LastName", "*") %>
</P>
<P>
<Label for = "Suffix"> Suffix: </label>
<% = Html. TextBox ("Suffix") %>
<% = Html. ValidationMessage ("Suffix", "*") %>
</P>
<P>
<Label for = "CompanyName"> CompanyName: </label>
<% = Html. TextBox ("CompanyName") %>
<% = Html. ValidationMessage ("CompanyName", "CompanyName cannot be blank") %>
</P>
<P>
<Label for = "SalesPerson"> SalesPerson: </label>
<% = Html. TextBox ("SalesPerson") %>
<% = Html. ValidationMessage ("SalesPerson", "*") %>
</P>
<P>
<Label for = "EmailAddress"> EmailAddress: </label>
<% = Html. TextBox ("EmailAddress") %>
<% = Html. ValidationMessage ("EmailAddress", "EmailAddress cannot be blank") %>
</P>
<P>
<Label for = "Phone"> Phone: </label>
<% = Html. TextBox ("Phone") %>
<% = Html. ValidationMessage ("Phone", "*") %>
</P>
<P>
<Label for = "PasswordHash"> PasswordHash: </label>
<% = Html. TextBox ("PasswordHash") %>
<% = Html. ValidationMessage ("PasswordHash", "*") %>
</P>
<P>
<Label for = "PasswordSalt"> PasswordSalt: </label>
<% = Html. TextBox ("PasswordSalt") %>
<% = Html. ValidationMessage ("PasswordSalt", "*") %>
</P>
<P>
<Label for = "rowguid"> rowguid: </label>
<% = Html. TextBox ("rowguid") %>
<% = Html. ValidationMessage ("rowguid", "*") %>
</P>
<P>
<Label for = "ModifiedDate"> ModifiedDate: </label>
<% = Html. TextBox ("ModifiedDate") %>
<% = Html. ValidationMessage ("ModifiedDate", "*") %>
</P>
<P>
<Input type = "submit" value = "Create"/>
</P>
</Fieldset>
<% }%>
<Div>
<% = Html. ActionLink ("Back to List", "Index") %>
</Div>
</Asp: Content>
If the Model generated by Entityframework is used and the database is not empty during design, the Nullable attribute of this field in the generated Model layer is false, even if no simple verification is performed on the Controller, in the View layer, whether or not it is null is also determined.
2. Use IDataErrorInfo Interface
The IDataErrorInfo interface is easy to define:
Public interface IDataErrorInfo {string this [string columnName] {get ;}string Error {get ;}}
To use IDataErrorInfo Interface, follow these steps:
Creates a Partial class for the Model.
Add OnChanging and OnChanged Partial Methods
Implement the IDataErrorInfo Interface
Use IdataErrorInfo
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Web;
Using System. ComponentModel;
Namespace MvcApplication4.Models
{
Public partial class Customer: IDataErrorInfo
{
Private Dictionary <string, string> _ errors = new Dictionary <string, string> ();
Partial void OnCompanyNameChanging (string value)
{
If (value. Trim (). Length = 0)
{
_ Errors. Add ("CompanyName", "CompanyName is required ");
}
}
Public string Error
{
Get
{
Return string. Empty;
}
}
Public string this [string columnName]
{
Get
{
If (_ errors. ContainsKey (columnName ))
{
Return _ errors [columnName];
}
Return string. Empty;
}
}
}
}
3. Use Data Annotation Validators
Download Data Annotations Model Binder sample, in http://aspnet.codeplex.com/Release/ProjectReleases.aspx? ReleaseId = 24471
Add references to Microsoft. Web. Mvc. DataAnnotations. dll and System. ComponentModel. DataAnnotations. dll
In the Application_Start () method of Global. asax. cs, configure
Use Data Annotation Validator Attributes
The System. ComponentModel. DataAnnotations namespace contains four attributes:
Range: Range Verification
ReqularExpression: Regular Expression Verification
Required: verification Required
StringLength: String Length Verification
Validation: This is the base class for all verification properties.
Use Data Annotation Validators
Using System. ComponentModel;
Using System. ComponentModel. DataAnnotations;
Namespace MvcApplication4.Models
{
Public class Test
{
Public int Id {get; set ;}
[Required]
[StringLength (10)]
Public string Name {get; set ;}
[Required]
Public string Description {get; set ;}
[DisplayName ("Price")]
[Required]
[RegularExpression (@ "^ \ $? \ D + (\. (\ d {2 }))? $ ")]
Public decimal UnitPrice {get; set ;}
}
}
Author: Shen Shan laolin blog: http://wlb.cnblogs.com/