ASP.NET MVC2 project үүсгээд доорхи кодыг Register.aspx дээр солиж тавиад ажиллуулаарай.
доорх код нь Jquery UI ашигласан хялбар $._DatePicker функц бичсэн байгаа ашиглахгүй байж болно гэхдээ энэ жишээн дээр DateTime төрлийн утгыг бас харуулж байгаа.
WebSiteRender ( Зохиомол Class ) програмчлалд хэрэгтэй WebSite ийн мэдээллийг агуулдаг.
<script type = "text/javascript">
$(function() {
$._DatePicker = function() {
var method = null;
var dformat = null;
if (arguments.length == 3) {
if (typeof arguments[2] == 'function') {
method = arguments[2];
} else {
dformat = arguments[2];
}
}
if (arguments.length == 4) {
dformat = arguments[2];
method = arguments[3];
}
if (arguments.length == 2 && typeof arguments[1] == 'function') {
method = arguments[1];
}
$(arguments[0]).datepicker({
showOn: "both",
buttonImage: "<%: WebSiteRender.Current.FullName %>/Scripts/jquery/images/calendar.gif",
buttonImageOnly: true,
showOtherMonths: true,
selectOtherMonths: true,
changeMonth: true,
changeYear: true,
onSelect: method,
dateFormat: dformat == null ? DEFAULT_DATE_FORMAT : dformat
});
//$("#" + $.datepicker._mainDivId).css("font-size", "77%");
if (arguments.length == 2 && typeof arguments[1] == 'string') {
$(arguments[0]).val(arguments[1]);
}
if (arguments.length == 3 && typeof arguments[1] == 'string') {
$(arguments[0]).val(arguments[1]);
}
};
});
</script>
// RegisterModel class ийг бусдад хэрэг болох үүднээс жаахан өөрчилсөн байгаа
<%: Html.LabelFor(m => m.UserName) %> бичиглэл нь Inherits="System.Web.Mvc.ViewPage<RegisterModel>" %> кодтой холбоотой ба Тухайн хуудасны Өгөгдөл хадгалах Model class д утга олгогдсон өгөгдлийг CAST хийж
(Model==RegisterModel as m) гэсэн үг бөгөөд
Html.LabelFor(m => m.UserName) код нь моделийн талбарыг Html код болгоно.
Мөн
<%: Html.DropDownListFor(m => m.SexType
, new SelectList(RegisterModel.SexTypes, "Value", "Text")
, "[ None ]") %>
код нь <select></select> html бичиглэл үүсгэх зорилготой функц юм.
RegisterModel.SexTypes нь анх Controller дуудагдах үед static member т утга оноосон олонлог.
m.SexType нь RegisterModel.SexTypes.Value утгыг авна.
Анх AccountController.Register() дуудагдахад RegisterModel нь null байна.
дарааа нь хадгалах үед Register(RegisterModel model) нь дүүргэгдэнэ.
Register.aspx
<%@ Page Language="C#" MasterPageFile="../Site.Master" Inherits="System.Web.Mvc.ViewPage<RegisterModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">Register</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<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 <%: ViewData["PasswordLength"] %> characters in length.
</p>
<% using (Html.BeginForm()) { %>
<%: Html.ValidationSummary(true, "Хадгалахад алдаа гарлаа!")
// Html.ValidationMessageFor(m => m.UserName) гэх мэт алдааны бусад мэдээлэл дээрх кодны доор (яг энд) харагдана
%>
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
<%: Html.LabelFor(m => m.UserName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.UserName) %>
<%: Html.ValidationMessageFor(m => m.UserName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.Email) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.Email) %>
<%: Html.ValidationMessageFor(m => m.Email) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.Password) %>
</div>
<div class="editor-field">
<%: Html.PasswordFor(m => m.Password) %>
<%: Html.ValidationMessageFor(m => m.Password) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.ConfirmPassword) %>
</div>
<div class="editor-field">
<%: Html.PasswordFor(m => m.ConfirmPassword) %>
<%: Html.ValidationMessageFor(m => m.ConfirmPassword) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.LastName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.LastName) %>
<%: Html.ValidationMessageFor(m => m.LastName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.FirstName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(m => m.FirstName) %>
<%: Html.ValidationMessageFor(m => m.FirstName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.SexType) %>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(m => m.SexType
, new SelectList(RegisterModel.SexTypes, "Value", "Text")
, "[ None ]") %>
<%: Html.ValidationMessageFor(m => m.SexType) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(m => m.BirthDay) %>
</div>
<div class="editor-field">
<%: Html.TextBox("BirthDay", Model.BirthDay)%>
<%: Html.ValidationMessageFor(m => m.BirthDay) %>
<script type="text/javascript">
$(function () {
$._DatePicker("#BirthDay");
});
</script>
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
</div>
<% } %>
</asp:Content>
Register(), Register(RegisterModel model) бичлэг нь <% using (Html.BeginForm()) { %> кодтой холбоотой ба анх хуудас дуудагдаж байхад model == null байх нь мэдээж учир Register() method ажиллаж, өгөгдөл хадгалах үед model == RegisterModel дүүргэгдэж Register(RegisterModel model) method дуудагдана. Хэрэв Register(RegisterModel model) оос өөр функц ажиллуулах бол Html.BeginForm("SaveUser", "AccountController", "POST") гэх мэтчилэн өөрчилж болно.
Миний хувьд Ria Service ( Domain Service Class ) өгөгдөл ашигладаг учир түүнтэй зохицдог Хэрэглэгчийн нэвтрэхтэй холбоотой нууцлалыг хангах доорх AuthenticationService маягийн кодыг ашигласан байна
AuthenticationDbContextHelper.cs
public class AuthenticationDbContextHelper
{
public static readonly AuthenticationDbContextHelper Current = new AuthenticationDbContextHelper();
private MyDbContext db = new MyDbContext();
private static readonly string RootEmail = "boroo_c@yahoo.com";
public bool ValidateUser(string username, string password)
{
return this.db.UserInfoes.Any(u => u.Name == username && u.Password == password);
}
public bool ValidateUser(string email, string username, string password)
{
return this.db.UserInfoes.Any(u => u.Email == email && u.Name == username && u.Password == password);
}
public UserInfo GetUser()
{
if (HttpContext.Current.Request.IsAuthenticated)
{
return this.GetUser(User.Identity.Name);
}
return null;
}
private UserInfo GetUser(string userName)
{
return this.db.UserInfoes.FirstOrDefault(u => u.Name == userName);
}
private UserInfo GetUser(string userName, string email)
{
return this.db.UserInfoes.FirstOrDefault(u => u.Name == userName && u.Email == email);
}
private UserInfo GetSingleUser(string email)
{
return this.db.UserInfoes.FirstOrDefault(u => u.Email == email);
}
private bool createRootUser(string email)
{
UserInfo root = new UserInfo();
root.LastName = "";
root.FirstName = "System User";
root.Name = SystemConstants.DbSystemUser;
root.Password = Util.STR(SystemConstants.DbPasswordMinLength);
root.Email = email;
root.BirthDay = new DateTime(1986, 4, 12);
root.SexTypeCode = (short)SexTypeEnum.male;
root.SiteId = 0;
root.DbRoles = SystemConstants.DbSystemRole;
root.IsActive = true;
root.Modified = root.Created = DateTime.Now;
root.ModifiedId = root.CreatedId = 0;
root.ModifiedName = root.CreatedName = ".";
this.db.UserInfoes.Add(root);
this.db.SaveChanges();
return true;
}
private void InitRoot()
{
if (!isCreatedRootUser())
{
createRootUser(RootEmail);
}
}
public UserInfo Login(string userName, string password, bool isPersistent, string customData)
{
InitRoot();
if (this.ValidateUser(userName, password))
{
UserInfo user = this.GetUser(userName);
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserId] = user.Id;
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserName] = user.Name;
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserEmail] = user.Email;
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserLastName] = user.LastName;
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserFirstName] = user.FirstName;
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserRole] = user.DbRoles;
FormsAuthentication.SetAuthCookie(userName, isPersistent);
return this.GetUser(userName);
}
return null;
}
public bool RegisterUser(string userData)
{
InitRoot();
if (userData == null) return false;
UserInfo user = Util.DeserializeX<UserInfo>(userData);
if (isCreatedAnyUser(user.Name))
{
return false;
}
IQueryable<UserInfo> query = this.db.UserInfoes.Where(u => u.Name.Equals(user.Name));
List<UserInfo> list = query.ToList<UserInfo>();
if (list.Count > 0) return false;
this.db.UserInfoes.Add(user);
this.db.SaveChanges();
return true;
}
public void UpdateUser(UserInfo user)
{
this.db.UserInfoes.Attach(user);
this.db.SaveChanges();
}
public UserInfo Logout()
{
FormsAuthentication.SignOut();
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserId] = null;
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserName] = string.Empty;
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserEmail] = string.Empty;
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserLastName] = string.Empty;
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserFirstName] = string.Empty;
System.Web.HttpContext.Current.Session[SystemSessionKeys.UserRole] = string.Empty;
return null;
}
public bool ChangePassword(string username, string oldPassword, string newPassword)
{
UserInfo user = GetUser(username);
if (user.Password.Equals(oldPassword))
{
user.Password = newPassword;
this.db.SaveChanges();
return true;
}
return false;
}
public bool ResetPassword(string username, string email)
{
InitRoot();
string sPassword = Util.STR(SystemConstants.DbPasswordMinLength);
UserInfo user = null;
try
{
user = GetUser(username, email);
}
catch { return false; }
if (user != null)
{
user.Password = sPassword;
this.db.SaveChanges();
string body = string.Format(HtmlMailResources.ResetPassword, sPassword, WebSites.Current.FullName);
if (user.Roles.Contains(SystemConstants.DbSystemRole))
{
MailUtil.systemMailSend(email, WebSites.Current.Name, body);
}
else
{
MailUtil.siteMailSend(email, WebSites.Current.Name, body, null);
}
return true;
}
return false;
}
public bool isCreatedAnyUser(string userName)
{
return this.db.UserInfoes.Any(u => u.Name == userName && u.SiteId == WebSites.Current.Id);
}
public bool isCreatedRootUser()
{
return this.db.UserInfoes.Any(u => u.Name == SystemConstants.DbSystemUser && u.SiteId == WebSites.Current.Id);
}
}
AccountController.cs
AuthenticationDbContextHelper _auth;
//// **************************************
//// URL: /Account/Register
//// **************************************
public ActionResult Register()
{
Model.MetaTitle = "Register";
ViewData["PasswordLength"] = 6;
return View();
}
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
UserInfo userInfo = new UserInfo();
userInfo.Name = model.UserName;
userInfo.Password = model.Password;
userInfo.Email = model.Email;
userInfo.FirstName = model.FirstName;
userInfo.LastName = model.LastName;
userInfo.BirthDay = model.BirthDay;
SexTypeEnum ste = (SexTypeEnum)Enum.Parse(typeof(SexTypeEnum), model.SexType);
userInfo.SexTypeCode = (short)ste;
userInfo.Roles = new List<string>();
userInfo.IsActive = 0;
FillRequiredFields_Date6_SiteId(userInfo);
string userData = DataManager.SerializeX(userInfo);
if (_auth.RegisterUser(userData))
{
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "error");
//AccountValidation.ErrorCodeToString(createStatus)
}
}
// If we got this far, something failed, redisplay form
ViewData["PasswordLength"] = 6;
return View(model);
}
No comments:
Post a Comment