一个登陆页面,在view的代码如下
@model shw2013.Models.adminLogin @{ Layout = null; } <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <div id="loginBox"> <div class="formBox"> @using (Html.BeginForm("checkAdminLogin", "Account", FormMethod.Post, new { name = "form1", id = "form1" })) { <div class="sft1"> <ul> <li>@Html.TextBoxFor(m => m.userAc)</li> <li>@Html.PasswordFor(m => m.userPwd)</li> <li><span style="float:left; width:75px; overflow:hidden;">@Html.TextBoxFor(m => m.userYZM, new { style = "width:58px;" })</span><span style="float:left;"><img style="width:38px; height:20px;" id="Logon-vcode" onclick="javascript:this.src='/Account/Vcode?id=Logon&time=' + (new Date()).getTime();" src="@Url.Action("Vcode", "Account", new { id = "Logon" })" /></span></li> </ul> </div> <div style="float:left;"> <a style="width:70px; margin-top:45px; height:35px;float:left;" href="#" onclick="javascript:document.form1.submit();"></a> </div> } </div> </div> </body> </html>
在Controllers对应的代码如下
public ActionResult checkAdminLogin(Models.adminLogin model) { if (ModelState.IsValid) { if ((string)Session["Logon"] == model.userYZM) { userInfo user = _userInfoDAL.getLoginUser(TextHelper.Html.InputText(TextHelper.Html.InputText(model.userAc,100), 30), TextHelper.Html.MD5(model.userPwd)); if (string.IsNullOrWhiteSpace(user.userMail)) { return Content("<script>alert('用户名或密码错误!');window.location.href='/Account/superLogin/';</script>"); } else { //如果不是管理员帐号一样提示错误 if (_userTypeDAL.getById(user.userType).TypeName != "管理员") { return Content("<script>alert('" + _userTypeDAL.getById(user.userType).TypeName + "不允许登录!');window.location.href='/Account/superLogin/';</script>"); } else { FormsAuthentication.SetAuthCookie("shwilynn", false);//保存票据 //添加登录日志 Log.Txt.add(model.userAc + "从IP" + Request.UserHostAddress + "登录了后台"); //存用户名 //存用户Id TextHelper.Html.setCookie("userId", user.Id.ToString()); return RedirectToAction("ilynn", "Admin"); } } } else { return Content("<script>alert('验证码错误!');window.location.href='/Account/superLogin/';</script>"); } } else { return Content("<script>alert('输入数据不完整!');window.location.href='/Account/superLogin/';</script>"); } }
这个是验证登陆的,那么问题来了, checkAdminLogin有一个model参数,而表单提交的action="/Account/checkAdminLogin",并没有一个地方传递model,是通过什么机制将输入框输入的信息转换为model对象并作为参数传递的呢?
@using (Html.BeginForm("checkAdminLogin", "Account", FormMethod.Post, new { name = "form1", id = "form1" }))
是这个,你不是包含在表单里面了吗,
@Html.TextBoxFor(m => m.userAc)</li>
@Html.PasswordFor(m => m.userPwd)
里面的文本值都是一一对应上你的实体类字段的,controller里面方法checkAdminLogin(Models.adminLogin model)参数里面自然就有数据带过来了。
你F12看看生成的html脚本,标签的name值,就是model的属性。其实就是不用你写Resquest["XXX"]的一个简化。