Asp.net MVC Linq to SQL Model verification

Models

 1     public class Student
 2     {
 3         public int Id { get; set; }
 4         [Required(ErrorMessage = "姓名不能为空!")]
 5         public string Name { get; set; }
 6         [Range(1, 100, ErrorMessage = "年龄只能在1-100之间!")]
 7         public int Age { get; set; }
 8         public string Sex { get; set; }
 9         [StringLength(10, ErrorMessage = "输入地址过长!")]
10         public string Address { get; set; }
11         [RegularExpression(@"[a-z,0-9,A-Z,_]+@\w+.((com|cn)|(net.cn|net))", ErrorMessage = "email格式不正确!")]
12         public string Email { get; set; }
13 
14     }
1     public class StudentEntity:DbContext
2     {
3         public DbSet<Student> Students { get; set; }
4 
5     }

Controllers

 1     public class HomeController : Controller
 2     {
 3         //
 4         // GET: /Home/
 5 
 6         public ActionResult Index()
 7         {
 8             return View();
 9         }
10         StudentEntity entity = new StudentEntity();
11         public ActionResult Add(Student stu)
12         {
13             if (ModelState.IsValid==true)
14             {
15                 entity.Students.Add(stu);
16                 entity.SaveChanges();
17             }
18             return View();
19         }
20 
21     }

View 

 1 @model Modelverification.Models.Student
 2 
 3 @{
 4     Layout = null;
 5 }
 6 
 7 <!DOCTYPE html>
 8 
 9 <html>
10 <head>
11     <meta name="viewport" content="width=device-width" />
12     <title>Index</title>
13     <script src="~/Scripts/jquery-1.8.2.min.js"></script>
14     <script src="~/Scripts/jquery.validate.min.js"></script>
15     <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
16 </head>
17 <body>
18     <div>
19         <form action="/Home/Add">
20             <table>
21                 <tr><td>姓名:</td><td>@Html.TextBoxFor(Model => Model.Name) @Html.ValidationMessageFor(Model => Model.Name)</td></tr>
22                 <tr><td>年龄:</td><td>@Html.TextBoxFor(Model => Model.Age) @Html.ValidationMessageFor(Model => Model.Age)</td></tr>
23                 <tr><td>地址:</td><td>@Html.TextBoxFor(Model => Model.Address) @Html.ValidationMessageFor(Model => Model.Address)</td></tr>
24                 <tr><td>email:</td><td>@Html.TextBoxFor(Model => Model.Email) @Html.ValidationMessageFor(Model => Model.Email)</td></tr>
25                 <tr><td>性别:</td><td>@Html.TextBoxFor(Model => Model.Sex) @Html.ValidationMessageFor(Model => Model.Sex)</td></tr>
26                 <tr><td><input type="submit" value="提交" /></td></tr>
27             </table>
28         </form>
29     </div>
30 </body>
31 </html>

 

posted @ 2018-10-17 16:20  Hao0  阅读(135)  评论(0编辑  收藏  举报