Introduction to ASP. net mvc (below)

Source: Internet
Author: User

Let's improve the verification function. In the system. componentmodel. dataannotations namespace, some basic attribute classes are available for verification. You only need to add these attributes to the model field. You can check msdn for specific attribute classes. An example is given below:

Publicclass movie
{
[Key, databasegenerated (databasegeneratedoption. Identity)]
Publicint ID {Get; set ;}
[Stringlength (10, minimumlength = 2, errormessage = "must be 2 ~ 10 characters long "), required, display (name =" name ")]
Publicstring title {Get; set ;}
[Display (name = "release date")]
Public datetime releasedate {Get; set ;}
Publicstring genre {Get; set ;}
[Range (1,100, errormessage = "must be 1 ~ (100 ")]
Publicdecimal price {Get; set ;}
Publicstring rating {Get; set ;}
}

Then run the program to see the effect:

Of course, the default verification is often not enough. You can try to change the date to 201-01-1 and click Create to cause an exception. We can add custom verification attributes to meet verification requirements. Next we will implement a dateattribute attribute to check the date format and date range. Create a dynamic link library biz. Web and add system. componentmodel. dataannotations references. Create a class as follows:

Using system;
Using system. Collections. Generic;
Using system. componentmodel. dataannotations;
Using system. Data. sqlclient;

Namespace biz. Web
{
[Attributeusage (attributetargets. Property | attributetargets. Field, allowmultiple = false)]
Publicclass dateattribute: validationattribute
{
Public dateattribute ()
{
// Set default Max and min time according to sqlserver datetime type
Mindate = new datetime (1753, 1, 1). tostring ();
Maxdate = new datetime (9999, 12, 31). tostring ();
}

Publicstring mindate
{
Get;
Set;
}

Publicstring maxdate
{
Get;
Set;
}

Private datetime mindate, maxdate;
// Indicate if the format of the input is really a datetime
Privatebool isformaterror = true;

Publicoverridebool isvalid (object value)
{
// Ignore it if no value
If (value = NULL | string. isnullorempty (value. tostring ()))
Returntrue;
// Begin check
String S = value. tostring ();
Mindate = datetime. parse (mindate );
Maxdate = datetime. parse (maxdate );
Bool result = true;
Try
{
Datetime date = datetime. parse (s );
Isformaterror = false;
If (date> maxdate | date <mindate)
Result = false;
}
Catch (exception)
{
Result = false;
}
Return result;
}

Publicoverridestring formaterrormessage (string name)
{
If (isformaterror)
Return "enter a valid date ";
Returnbase. formaterrormessage (name );
}
}
}

The isvalid method is mainly implemented. If necessary, the formaterrormessage method can be implemented. Note that attribute parameters can only be of a limited number of types. Refer to here. After writing it, add biz. Web reference to the helloworld project and use it. For example:

[Display (name = "release date"), date (maxdate = "2012-01-01", errormessage = "2012 ")]
Public datetime releasedate {Get; set ;}

See the following results:

Of course, this method has many restrictions, mainly the limitation of attribute parameters. It can only be a basic type and can only be a constant. For more complex verification rules, see here:

Implement remote validation in ASP. net mvc.

Some screening functions are added to the Lndex page. You can pass parameters to the index for filtering. Add a selectbox on the page to filter the genre field and change the moviecontroller method:

Public viewresult index (string moviegenre)
{
VaR genre = (from S in db. Movies
Orderby S. Genre
Select S. Genre). Distinct ();
Viewbag. moviegenre = new selectlist (genre); // prepare data from the drop-down list for the foreground.
If (! String. isnullorempty (moviegenre ))
{
// Filter
VaR movies = from S in db. movies where S. Genre = moviegenre select s;
Return view (movies );
}
Return view (db. Movies. tolist ());
}

On the view page, add a form with a selection box and a button. The Code is as follows:

@ Using (html. beginform ("Index", "movie", formmethod. Get ))
{
<P> genre: @ html. dropdownlist ("moviegenre", "all") <input type = "Submit" value = ""/> </P>
}

The effect is as follows:

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.