First ,model It's through ef Automatic is the generated entity .

Adding model annotation means to automatically verify whether the information filled in by the user meets our requirements when registering ( That's what we need for this example )

Let's show you the effect first .

then Email You can only see the effect after you click Register

Now let's recall the process with me

We don't talk about entities anymore , No matter how you create it , Now let's talk about adding model annotations :

First add a class , Then add two important references to the namespace :

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

Here is a brief introduction MVC Common comments :

Required: Validation required

StringLength: Verify the maximum length of the field

Range: Verify field range

RegularExpression: Custom validation rules

DisplayName: Field display name

Then we write the code in our new class

First, make sure that the new class's namespace is consistent , If your entity class is built in the root of the project , And your annotation class is Models Under the folder , Then the above effect will not appear , I have encountered such problems when I was doing it

And then there's code time :

 public class EmailAttribute : RegularExpressionAttribute
{
public EmailAttribute()
: base(@"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$")
{
}
} [MetadataType(typeof(UserMetadata))]
public partial class Tb_User
{
public string RePwd { get; set; }
}
/// <summary>
/// Add features to the entity class DisplayName
/// </summary>
public class UserMetadata
{
[DisplayName(" user name ")]
[Remote("NotExitesUserName", "Home",ErrorMessage=" The user account already exists ")]
public string UserName { get; set; }
/// <summary>
/// In the entity class is Remark Property settings DataType characteristic , Specify as multiline text
/// </summary>
[DataType(DataType.MultilineText)]
[DisplayName(" remarks ")]
public string Remark { get; set; }
[DisplayName(" Age ")]
[Range(, )]
public int Age { get; set; }
[PasswordPropertyText]
[DisplayName(" password ")]
public string Pwd { get; set; }
[PasswordPropertyText]
[DisplayName(" Retype password ")]
[System.Web.Mvc.Compare("Pwd")]
public string RePwd { get; set; }
[Email]
public string Email { get; set; } }

The annotation class is finished , We're going to write the controller

Add one HOME controller

The code is as follows :

 private NorthwindEntities1 db = new NorthwindEntities1();
//
// GET: /Home/
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(Tb_User model)
{
if (ModelState.IsValid)
{
db.Tb_User.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View();
}
}
[HttpGet]
public JsonResult NotExitesUserName()
{
string UserName = Request.Params["UserName"]; var user = db.Tb_User.Where(x => x.UserName == UserName).FirstOrDefault();
return user == null ? Json(true, JsonRequestBehavior.AllowGet) : Json(false, JsonRequestBehavior.AllowGet);
}
public ActionResult Index()
{
var user = db.Tb_User.ToList();
return View(user);
}
}

here private NorthwindEntities1 db = new NorthwindEntities1(); It's the model of my entity class , use EF add to ADO.NET Created by entity

And then there's the corresponding add view

First of all Register View :

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> <h2>@ViewBag.Title</h2>
@using(Html.BeginForm("Register",null,FormMethod.Post))
{
<table><tr><td>@Html.DisplayNameFor(x=>x.UserName):</td><td>@Html.TextBoxFor(x=>x.UserName) @Html.ValidationMessageFor(x=>x.UserName)</td></tr>
<tr><td>@Html.DisplayNameFor(x=>x.Age):</td><td>@Html.TextBoxFor(x=>x.Age)@Html.ValidationMessageFor(x=>x.Age)</td></tr>
<tr><td>@Html.DisplayNameFor(x=>x.Pwd):</td><td>@Html.PasswordFor(x=>x.Pwd)@Html.ValidationMessageFor(x=>x.Pwd)</td></tr>
<tr><td>@Html.DisplayNameFor(x=>x.RePwd):</td><td>@Html.PasswordFor(x=>x.RePwd)@Html.ValidationMessageFor(x=>x.RePwd)</td></tr>
<tr><td>@Html.DisplayNameFor(x=>x.Email):</td><td>@Html.TextBoxFor(x=>x.Email)@Html.ValidationMessageFor(x=>x.Email)</td></tr>
<tr><td>@Html.DisplayNameFor(x=>x.Remark):</td><td>@Html.TextBoxFor(x=>x.Remark)@Html.ValidationMessageFor(x=>x.Remark)</td></tr>
<tr><td colspan=""><input type="submit" value=" register "/></td></tr>
</table>
}

The steps to create a view here are :

among Script You can pull it yourself , You can also tap with your hands .

Add again Index View , This is a direct reference to List Templates

So basically OK 了 , And then run the project , First add a test data , Then the verification can achieve the effect we showed at the beginning of the above

MVC More articles on model annotation

  1. MVC Model annotations in

    authour: chenboyi updatetime: 2015-04-26 21:28:42 friendly link:   Catalog : 1, Mind mapping 2, Content analysis 3,CodeSimple 1, ...

  2. MVC Validation of the ( A combination of model annotations and non intrusive scripting )

    @HtmlHrlper Tags created in this way , Some properties will be generated automatically , Some of these properties are about validation As shown in the figure : Model annotations After model annotation ,MVC Validation of the , Including the front end client , Background server verification ,MVC It's all done, including , Even if the user ...

  3. MVC Validation of the ( A combination of model annotations and non intrusive scripting ) .Net In the middle of the world Redis .net Send email by code Log4net (Log for .net) Use GDI Technology creation ASP.NET Verification Code Razor template engine (RazorEngine) .Net Regular expressions that programmers should master

    MVC Validation of the ( A combination of model annotations and non intrusive scripting )   @HtmlHrlper Tags created in this way , Some properties will be generated automatically , Some of these properties are about validation As shown in the figure : Model annotations After model annotation ,MVC Validation of the , Including front desk guests ...

  4. be based on spring mvc Annotations DEMO Complete example

    Abandoned struts, use spring mvc The framework did several projects , It feels good , And it uses annotations , You can save a lot of configuration files . This article mainly introduces the use of annotation configuration spring mvc, Previously written spring3.0 mv ...

  5. Asp.Net MVC Model validation details - Implement client 、 Server side double verification

    Summary stay asp.net webform In development, the information submitted by users is often checked , Generally, for the sake of security, we will do it on the client side Javascript( It's good for interaction ). Server double check ( Security ). Writing verification code is a tedious process ...

  6. spring mvc Annotation based Usage Summary

    In this paper, from http://blog.csdn.net/lufeng20/article/details/7598801 summary Following Spring 2.0 Yes Spring MVC After a major upgrade ,Sprin ...

  7. ASP.NET MVC Model bound 6 A suggestion ( Reprint )

    ASP.NET MVC Model bound 6 A suggestion Published in 2011-08-03 10:25| Source: blog Garden | 31  comments | Author champion validationasp.netmvc.netasp Abstract :ASP.NET ...

  8. Spring MVC Learning summary (2)——Spring MVC Common notes

        Use Spring MVC Note and its usage and other related knowledge to realize the controller function . 02      Before using Struts2 Realization MVC When you annotate , With the help of struts2-convention This plugin , Now we make ...

  9. Asp.Net MVC Model ( Use Entity Framework Create model classes ) - Part.1

    The purpose of this tutorial is to explain how to create ASP.NET MVC Application time , How to use Microsoft Entity Framework To create a data access class . This tutorial assumes that you have a prior understanding of Microsoft Entity Fram ...

Random recommendation

  1. utilize git+hugo+markdown Build a static website

    utilize git+hugo+markdown Build a static website I always want to have my own document management system : It's easy to write , And the corresponding documents are easy to share Very convenient storage . management . Historical record Browsing and querying in comparison The first point is to use M ...

  2. [XAF] How to set List View Columns Title Customization align center?

    https://www.devexpress.com/Support/Center/Question/Details/T423138

  3. Docker- Data volumes and data container volumes

    There are two main ways to manage data in containers : Data volume (Data Volumes) Data volume container (Data Volumes Dontainers) Data volume Use -v You can mount a local directory into a container as a data volume . [root ...

  4. C# WinForm Development series - RDLC

    http://www.cnblogs.com/peterzb/archive/2009/07/08/1519489.html http://jingyan.baidu.com/article/ab69 ...

  5. SQLite Simple application of

    Installation and deployment 1) Get into SQL The download page :http://www.sqlite.org/download.html 2) Download the precompiled binary package . Windows The environment is as follows : After downloading , Even if the deployment is complete .(P ...

  6. c++ Consortium

    The memory size allocated by the consortium is the size of the largest variable in the member variables The member variables of the Federation share memory Small segment mode (X86 Namely ) There are low address units in the low bit data Big end model                      There is a low address unit in the high byte

  7. zabbix Deployment of Distributed Monitoring

    zabbix It's a distributed surveillance , Management system , be based on server-clinet framework , It can be used to monitor various network services , Server and network machine etc . server Terminal base on C Language ,web The management end Frontend Is based on PHPA Make ...

  8. DJANGO_SETTINGS_MODULE is undefined The solution of error reporting

    problem : ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is ...

  9. efficient JavaScript

    Avoid using  eval  or  Function  Constructors rewrite  eval If you need a function , Use function Do not use  with Don't use... In functions that require performance  try-catch-finally Isolation  ev ...

  10. iOS Design patterns - Combine

    iOS Design patterns - Combine Schematic diagram explain Combine objects into a tree structure to represent “ part - whole ” Hierarchical structure , The composition mode makes the use of single object and composite object consistent . The key to mastering the combination pattern is to understand it clearly “ part / whole ” also ...