mvc框架下,使用jquery来验证表单,Membership采用自定义表的方式

1.webconfig设置

新建一mvc项目,如图,取名为mvcMembership

CreateProject





 

修改web.config

<connectionStrings>
<add name="ApplicationServices" connectionString="Data Source=CONAN;Initial Catalog=aspnetdb;Integrated Security=True" 
providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web><authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880"/>
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, 
System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" 
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" 
passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" 
passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="/"/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0,
 Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" 
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" 
type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
</roleManager>

2.添加action(表单验证检查用户名)

在AccountController.cs中添加

   public class AccountController : Controller
{...
    /// <summary>
        /// check user name 0-false.1-true
        /// </summary>
        /// <returns></returns>
       [AcceptVerbs(HttpVerbs.Get)]
        public JsonResult CheckUser(string username)
        {
            int nResult = 0;
            if (!string.IsNullOrEmpty(username))
                nResult = MembershipService.CheckUser(username)?1:0;
                 //ViewData["CheckUser"] = bResult;      //对于ajax 没用,取不到数据
           ////方法1
           // Response.Write(nResult);
           // Response.End();             //这句必须,否则出现server busy(服务器忙的错误),因为 datatype: "json"
           // return ActionResult();
           //方法2
            return this.Json(nResult);
        }

3.Add View
    右键点击account->add->view,取名为checkuser
addview

     不要masterpage,我们用来返回用户名检查的

4.MEMBERSHIP扩展用户数据库的设计

use aspnetdb;
if exists (select 1
from  sysobjects
where  id = object_id('dbo.aspnet_UserInfo')
and   type = 'U')
drop table dbo.aspnet_UserInfo
go
create table dbo.aspnet_UserInfo (
UserId               uniqueidentifier     not null,
UserName             varchar(256)         not null,
QQ                   varchar(30)          null,
MSN                  varchar(200)         null,
constraint PK_USERINFO primary key (UserId)
on "PRIMARY"
)

4.编写LINQ

 

          在models上右键->add new item
       新建一个LINQ to SQL class
       UserInfo.dbml(如图)
       linq
        在AccountController.cs中
          注意,我们把QQ,MSN卸载方法的传入参数里就可以传过来了,LINQ不是重点,我觉着用着方便而已
        /// <summary>
/// user registe
/// </summary>
/// <param name="userName"></param>
/// <param name="email"></param>
/// <param name="password"></param>
/// <param name="confirmPassword"></param>
/// <param name="QQ"></param>
/// <param name="MSN"></param>
/// <returns></returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string userName, string email, string password,
          string confirmPassword, string QQ, string MSN)
{
ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
if (ValidateRegistration(userName, email, password, confirmPassword))
{
// Attempt to register the user
MembershipCreateStatus createStatus = MembershipService.
                                             CreateUser(userName, password, email);
if (createStatus == MembershipCreateStatus.Success)
{
MembershipUserCollection users = Membership.GetAllUsers();
string strUserID = users[userName].ProviderUserKey.ToString();
//insert user info useing linq
UserInfoDataContext db = new UserInfoDataContext();
aspnet_UserInfo extinfo = new aspnet_UserInfo();
extinfo.UserId = new Guid(strUserID);
extinfo.UserName = userName;
extinfo.QQ = QQ;
extinfo.MSN = MSN;
db.aspnet_UserInfos.InsertOnSubmit(extinfo);
db.SubmitChanges();
FormsAuth.SignIn(userName, false /* createPersistentCookie */);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("_FORM", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View();
}

5.设计register.asp

 <h2>
Create a New Account</h2>
<p>
Use the form below to create a new account.
</p>
<p>
Passwords are required to be a minimum of
<%=Html.Encode(ViewData["PasswordLength"])%>
characters in length.
</p>
<%= Html.ValidationSummary("Account creation was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm("Register", "Account", FormMethod.Post,
 new { @onsubmit = "return jQuery.formValidator.pageIsValid();" }))
{ %>
<div>
<fieldset>
<legend>Account Information</legend>
<table cellpadding="0" cellspacing="0" style="width: 90%">
<tr>
<td class="CaptionCell">
<label for="username">
Username:</label>
</td>
<td class="ContentCell">
<%= Html.TextBox("username", "", new { @class = "InputNormal" })%>
</td>
<td class="TipCell">
<div id="usernameTip">
</div>
</td>
</tr>
<tr>
<td class="CaptionCell">
<label for="password">
Password:</label>
</td>
<td class="ContentCell">
<%= Html.Password("password", "", new { @class = "InputNormal" })%>
</td>
<td class="TipCell">
<div id="passwordTip">
</div>
</td>
</tr>
<tr>
<td class="CaptionCell">
<label for="confirmPassword">
Confirm password:</label>
</td>
<td class="ContentCell">
<%= Html.Password("confirmPassword", "", new { @class = "InputNormal" })%>
</td>
<td class="TipCell">
<div id="confirmPasswordTip">
</div>
</td>
</tr>
<tr>
<td class="CaptionCell">
<label for="email">
Email:</label>
</td>
<td class="ContentCell">
<%= Html.TextBox("email", "", new { @class = "InputNormal" })%>
</td>
<td class="TipCell">
<div id="emailTip">
</div>
</td>
</tr>
<tr>
<td class="CaptionCell">
<label for="QQ">
QQ:</label>
</td>
<td class="ContentCell">
<%= Html.TextBox("QQ", "", new { @class = "InputNormal" })%>
</td>
<td class="TipCell">
<div id="QQTip">
</div>
</td>
</tr>
<tr>
<td class="CaptionCell">
<label for="QQ">
MSN:</label>
</td>
<td class="ContentCell">
<%= Html.TextBox("MSN", "", new { @class = "InputNormal" })%>
</td>
<td class="TipCell">
<div id="MSNTip">
</div>
</td>
</table>
<p>
<input id="submit" type="submit" value="Register" />
</p>
</fieldset>
</div>
<% } %>
</asp:Content>

 

客户端检查我们用jquery和猫冬写的formValidator3.5

 <script language="javascript" type="text/javascript">
function GetQueryString(val) {
var paraUsername=encodeURI(encodeURI(val));
return paraUsername;
}
$(document).ready(function() {
$.formValidator.initConfig();
$("#username").formValidator({ onshow: "please input username", onfocus: "username required", oncorrect: "OK" })
.inputValidator({ min: 1, empty: { leftempty: false, rightempty: false, emptyerror: "left side or right side cant not be blank" },
 onerror: "username required" })
.ajaxValidator({
type: "get",
url: "checkuser",
datatype: "json",
success: function(responseText) {
if (responseText == "1") {
return true;
}
else {
return false;
}
},
buttons: $("#button"),
error: function() { alert("server busy,try later..."); },
onerror: "username exits",
onwait: "user name checking,please wait..."
});
$("#password").formValidator({ onshow: "please input password", onfocus: "password required", oncorrect: "OK" })
.inputValidator({ min: 6, empty: { leftempty: false, rightempty: false, 
emptyerror: "left side or right side cant not be blank" }, 
onerror: "password length at least 6" });
$("#confirmPassword").formValidator({ onshow: "please confirm password", 
                      onfocus: "password confirm", oncorrect: "OK" })
.inputValidator({ min: 6, empty: { leftempty: false, rightempty: false, emptyerror: "left side or right side cant not be blank" }, 
onerror: "empty confirm password" }).compareValidator({ desid: "password", operateor: "=", onerror: "password not matched" });
$("#email").formValidator({ onshow: "please input your email", onfocus: "please input your email", oncorrect: "OK" })
.inputValidator({ min: 6, max: 100, onerror: "invaliad email" })
.regexValidator({ regexp: "^([\\w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([\\w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$", 
onerror: "invalid email" });
$("#QQ").formValidator({ empty: true, onshow: "please input your QQ", onfocus: "please input your QQ", oncorrect: "OK", 
onempty: "OK,raally haven't QQ?" }).inputValidator({ min: 5, max: 100, onerror: "invaliad QQ" })
.regexValidator({ regexp: "^[0-9]{5,}$", onerror: "QQ must be numbers" });
$("#MSN").formValidator({ empty: true, onshow: "please input your MSN", onfocus: "please input your MSN", 
oncorrect: "OK", onempty: "OK,raally haven't MSN?" })
.regexValidator({ regexp: "^([\\w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([\\w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$", 
onerror: "invalid msn" });
});
</script>

这样成功了 ,

register

代码演示和下载 我的个人网站 (自家机子,白天开机),另外各位兄弟姐妹有无锡的.net工作,给我介绍一下拉,谢谢
有什么疑问,qq 592038923, panfeng77@126.com

posted @ 2009-05-04 14:02  柯南  阅读(1403)  评论(0编辑  收藏  举报