这部分学习的主要内容是实现登陆时的用户名及密码验证,注册信息验证。里面涉及到Strongly-Type HtmlHelper 强类型的HtmlHelper辅助方法,数据验证的方式等等。其中强类型辅助方法是通过lamda表达式引用模板中的模型来传到视图上的。下面是实现过程:
1:打开vs2010->New Project->mvc2 web application ,我给solution命名为MvcValidate,添加后工程就已经创建好了。
2:建立User sqlserver 数据库,表UserInfo如下:
3:EF实现存储模型到概念模型的映射。右击Model文件夹 Add New Item 添加Entity Data Model 取名为UserModel,这是出现UserModel.edmx文件,在他的设计文件UserModel.Designer.cs文件中的Entities部分。找到UserInfo这个类,即public partial class UserInfo : EntityObject 对所映射的字段加上[Display Name] 属性。(为了后面强类型Html.LabelFor可以直接读取到其值),如[DisplayName("用户名:")]。代码如下:
2 /// No Metadata Documentation available.
3 ///</summary>
4 [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
5 [DataMemberAttribute()]
6 [DisplayName("用户编号:")]
7 publicglobal::System.Int32 UserID
8 {
9 get
10 {
11 return _UserID;
12 }
13 set
14 {
15 if (_UserID != value)
16 {
17 OnUserIDChanging(value);
18 ReportPropertyChanging("UserID");
19 _UserID = StructuralObject.SetValidValue(value);
20 ReportPropertyChanged("UserID");
21 OnUserIDChanged();
22 }
23 }
24 }
25 privateglobal::System.Int32 _UserID;
26 partialvoid OnUserIDChanging(global::System.Int32 value);
27 partialvoid OnUserIDChanged();
28
29 ///<summary>
30 /// No Metadata Documentation available.
31 ///</summary>
32 [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
33 [DataMemberAttribute()]
34 [DisplayName("用户名:")]
35 publicglobal::System.String UserName
36 {
37 get
38 {
39 return _UserName;
40 }
41 set
42 {
43 OnUserNameChanging(value);
44 ReportPropertyChanging("UserName");
45 _UserName = StructuralObject.SetValidValue(value, false);
46 ReportPropertyChanged("UserName");
47 OnUserNameChanged();
48 }
49 }
50 privateglobal::System.String _UserName;
51 partialvoid OnUserNameChanging(global::System.String value);
52 partialvoid OnUserNameChanged();
53
54 ///<summary>
55 /// No Metadata Documentation available.
56 ///</summary>
57 [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
58 [DataMemberAttribute()]
59 [DisplayName("用户地址:")]
60 publicglobal::System.String UserAddress
61 {
62 get
63 {
64 return _UserAddress;
65 }
66 set
67 {
68 OnUserAddressChanging(value);
69 ReportPropertyChanging("UserAddress");
70 _UserAddress = StructuralObject.SetValidValue(value, false);
71 ReportPropertyChanged("UserAddress");
72 OnUserAddressChanged();
73 }
74 }
75 privateglobal::System.String _UserAddress;
76 partialvoid OnUserAddressChanging(global::System.String value);
77 partialvoid OnUserAddressChanged();
78
79 ///<summary>
80 /// No Metadata Documentation available.
81 ///</summary>
82 [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
83 [DataMemberAttribute()]
84 [DisplayName( "用户密码:")]
85 publicglobal::System.String UserPwd
86 {
87 get
88 {
89 return _UserPwd;
90 }
91 set
92 {
93 OnUserPwdChanging(value);
94 ReportPropertyChanging("UserPwd");
95 _UserPwd = StructuralObject.SetValidValue(value, false);
96 ReportPropertyChanged("UserPwd");
97 OnUserPwdChanged();
98 }
99 }
100 privateglobal::System.String _UserPwd;
101 partialvoid OnUserPwdChanging(global::System.String value);
102 partialvoid OnUserPwdChanged();
103
104 ///<summary>
105 /// No Metadata Documentation available.
106 ///</summary>
107 [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
108 [DataMemberAttribute()]
109 [DisplayName("用户电话:")]
110 publicglobal::System.String UserPhone
111 {
112 get
113 {
114 return _UserPhone;
115 }
116 set
117 {
118 OnUserPhoneChanging(value);
119 ReportPropertyChanging("UserPhone");
120 _UserPhone = StructuralObject.SetValidValue(value, false);
121 ReportPropertyChanged("UserPhone");
122 OnUserPhoneChanged();
123 }
124 }
125 privateglobal::System.String _UserPhone;
126 partialvoid OnUserPhoneChanging(global::System.String value);
127 partialvoid OnUserPhoneChanged();
3:实现代码。直接在HomeController.cs下初始化UserEntities实体容器。
public UserEntities userContext;
public HomeController()
{
userContext = new UserEntities();
}
先创建一个登陆页面Login.aspx. 在HomeController.cs下添加代码
public ActionResult Login()
{
return View();
}
然后在Login区域右击Add View添加Login.aspx页面,此处需要注意添加的是强类型Stongly Type view ,class选 MvcValidate.Models.UserInfo(如果不可选,可能是models 的namespace没在该页using,完后编译一下即可。我所碰到过的问题O(∩_∩)O~)
添加Login.aspx页的Html代码如下:
2 <h2>
3 Login</h2>
4 <center>
5 <%using (Html.BeginForm())
6 { %>
7 <%=Html.ValidationSummary("请输入正确的用户名及密码,然后再试一次!") %>
8 <fieldset style="width: 350px">
9 <legend style="width: 350px; background: gray; display: block;">用户信息</legend>
10 <br />
11 <p>
12 <%=Html.LabelFor(m=>m.UserName)%>
13 <%=Html.TextBoxFor(m=>m.UserName) %>
14 <%=Html.ValidationMessageFor(m=>m.UserName,"*") %>
15 </p>
16 <p style="word-spacing: 1em">
17 <%=Html.LabelFor(m=>m.UserPwd)%><%=Html.PasswordFor(m=>m.UserPwd)%>
18 <%=Html.ValidationMessageFor(m=>m.UserPwd, "*")%></p>
19 <br />
20 </fieldset>
21 <p>
22 <input type="submit" value="submit"/>
23 <input type="reset" value="reset"/>
24 如果是未注册用户请先:<%=Html.ActionLink("Register", "Register")%></p>
25 <h2>
26 <p>
27 <%=ViewData["success"]%>
28 </p>
29 </h2>
30 <%} %></center>
31 </asp:Content>
Post提交后的控制页面的代码为:
2 public ActionResult Login(string UserName,string UserPwd,string UserPhone,string UserAddress,FormCollection from)
3 {
4 try
5 {
6 if (string.IsNullOrEmpty(UserName))
7 {
8 ModelState.AddModelError("UserName", "用户名不能为空");
9 }
10 if (string.IsNullOrEmpty(UserPwd))
11 {
12 ModelState.AddModelError("UserPwd", "用户密码不能为空");
13 }
14
15 UserExist(UserName, UserPwd);
16 if (ModelState.IsValid)
17 {
18 ViewData["success"] ="登陆成功!";
19 }
20 else
21 {
22 ViewData["success"] ="登陆失败!";
23 }
24 return View();
25 }
26 catch
27 {
28 ViewData["success"] ="登陆失败!";
29 return View();
30 }
31 }
其中验证密码和用户名的函数UserExist的代码如下:
2 {
3 List<string> userstr =new List<string>();
4 List<UserInfo> users =new List<UserInfo>();
5 users = userContext.UserInfos.ToList();
6 Dictionary<string, string> dicUser =new Dictionary<string, string>();
7 foreach (var u in users)
8 {
9 userstr.Add(u.UserName.Trim());
10 dicUser.Add(u.UserName.Trim(), u.UserPwd.Trim());
11 }
12 if (userstr.Contains(UserName))
13 {
14
15 if (dicUser[UserName]!= UserPwd){
16
17 ModelState.AddModelError("UserPwd", "用户密码错误!");
18 }
19
20 }
21 else
22 {
23 ModelState.AddModelError("UserName", "用户名不存在");
24 }
25 }
同样的方法添加Register.aspx注册页面,强类型才class也选MvcValidate.Models.UserInfo。 添加过程及代码为:
public ActionResult Register()
{
return View();
}
2 public ActionResult Register(string UserName, string UserPwd, string UserPhone, string UserAddress, FormCollection form)
3 {
4 if (string.IsNullOrEmpty(UserName))
5 {
6 ModelState.AddModelError("UserName", "用户名不能为空");
7 }
8 if (string.IsNullOrEmpty(UserPwd))
9 {
10 ModelState.AddModelError("UserPwd", "用户密码不能为空");
11 }
12 if (string.IsNullOrEmpty(UserPhone))
13 {
14 ModelState.AddModelError("UserPhone", "用户电话不能为空");
15 }
16 if (string.IsNullOrEmpty(UserAddress))
17 {
18 ModelState.AddModelError("UserAddress", "用户地址不能为空");
19 }
20 if (ModelState.IsValid)
21 {
22 UpdateModel(form);
23 ViewData["Reg"] ="注册成功!";
24 }
25 else
26 ViewData["Reg"] ="注册失败!";
27 return View();
28 }
Register页面的Html代码如下:
2 <h2>注册用户</h2>
3 <center>
4 <%using (Html.BeginForm())
5 { %>
6 <%=Html.ValidationSummary("请确认您的信息然后再试一次!") %>
7 <fieldset style=" width:350px">
8 <legend style=" width:350px;background: gray;">用户注册信息</legend>
9 <p style="word-spacing: 1em">
10 <%=Html.LabelFor(m => m.UserName)%>
11 <%=Html.TextBoxFor(m=>m.UserName) %>
12 <%=Html.ValidationMessageFor(m => m.UserName, "*")%>
13 </p>
14 <p style="word-spacing: 1em">
15 <%=Html.LabelFor(m=>m.UserPwd)%>
16 <%=Html.PasswordFor(m => m.UserPwd)%>
17 <%=Html.ValidationMessageFor(m => m.UserPwd, "*")%></p>
18 <p>
19 <%=Html.LabelFor(m => m.UserPhone)%>
20 <%=Html.TextBoxFor(m => m.UserPhone)%>
21 <%=Html.ValidationMessageFor(m => m.UserPhone, "*")%></p>
22 <p>
23 <%=Html.LabelFor(m => m.UserAddress)%>
24 <%=Html.TextAreaFor(m=>m.UserAddress) %>
25 <%=Html.ValidationMessageFor(m => m.UserAddress, "*")%></p>
26 </fieldset>
27 <p>
28 <input type="submit" value="Register"/>
29 <input type="reset" value="reset"/>
30 </p>
31 <h2>
32 <p>
33 <%=ViewData["Reg"] %></p>
34 </h2>
35 <%} %></center>
36 </asp:Content>
37
运行代码要改Global.asax下的routes.MapRoute的Action为Login,执行后的效果为:
Longin界面:
校验后的错误信息显示界面:
如果登陆成功,则显示“登陆成功”
Register界面为:
Register错误信息界面:
验证的错误信息可不用显示在前页,可以显示在对应的文本框后面,取消Html.ValidatonSummary这句,然后在Html.ValidationMessage()中将*号去掉,这是会显示对应的错误信息
如: