public async Task <ActionResult> Register(RegisterViewModel model) { if (!ModelState.IsValid) { return(View(model)); } try { var result = await _client.RegisterAsync(model.FullName, model.Email, model.Password); if (result.Body.RegisterResult.Success) { MembershipHelper.SignIn(result.Body.RegisterResult.Result); MvcCaptcha.ResetCaptcha(ControlHelper.CAPTCHA_KEY); return(RedirectToLocal()); } else { ModelState.AddModelError("", result.Body.RegisterResult.Error); } } catch (StockException exception) { ModelState.AddModelError("", exception.Message); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Index(FaucetViewModel model) { var mvcCaptcha = new MvcCaptcha(nameof(FaucetViewModel)); if (!mvcCaptcha.Validate(model.CaptchaCode)) { ModelState.AddModelError(nameof(model.CaptchaCode), "Invalid captcha"); return(View(model)); } if (!model.To.IsValidEthereumAddressHexFormat()) { ModelState.AddModelError(nameof(model.To), "Invalid address"); return(View(model)); } var rskService = new RskService(); var transaction = await rskService.SendTransaction(model.To, 0.001m); model.TransactionHash = transaction; return(View(model)); }
public ActionResult LoginComCaptcha(AutenticacaoModel usuario) { MvcCaptcha.ResetCaptcha("LoginCaptcha"); ViewBag.IncluirCaptcha = Convert.ToBoolean(ConfigurationManager.AppSettings["AD:DMZ"]); try { if (ModelState.IsValid) { AutorizacaoProvider.Logar(usuario); if (!string.IsNullOrWhiteSpace(usuario.Nome)) { return(Json(new { url = usuario.Nome.Replace("$", "&") })); } else { return(Json(new { url = Url.Action(ConfigurationManager.AppSettings["Web:DefaultAction"], ConfigurationManager.AppSettings["Web:DefaultController"]) })); } } return(View("Login", usuario)); } catch (Exception ex) { return(Json(new { alerta = ex.Message, titulo = "Oops! Problema ao realizar login..." })); } }
public async Task <ActionResult> ResetPassword(PasswordResetViewModel model) { if (ModelState.IsValid) { if (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Code)) { if (_authRepository.CanResetPassword(model.Email, model.Code)) { var result = _authRepository.ResetPassword(model.Email, model.Password); if (result.Success) { MvcCaptcha.ResetCaptcha("ChangePasswordCaptcha"); _logger.Debug(string.Format("The password for {0} has successfully been reset.", model.Email)); return(RedirectToAction("ResetPasswordConfirmation")); } } MvcCaptcha.ResetCaptcha("ChangePasswordCaptcha"); return(RedirectToAction("ResetFailed")); } } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { if (!ValidateGmail(model.Email, model.Password)) { ModelState.AddModelError("", "Gmail account doesn't exist"); return(View(model)); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, false, false); MvcCaptcha.ResetCaptcha("SampleCaptcha"); Session[Settings.KEYS.PSW_SESSION_KEY] = model.Password; return(RedirectToAction("Index", "Mailbox")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public IActionResult ContatoAcao([FromForm] Contato contato) { try { string userInput = HttpContext.Request.Form["CaptchaCode"]; MvcCaptcha mvcCaptcha = new MvcCaptcha("ExampleCaptcha"); if (!mvcCaptcha.Validate(userInput)) { ViewData["CONTATO"] = contato; return(View("Contato", contato)); } ModelState.Remove("captchacode"); if (ModelState.IsValid) { _gerenciarEmail.EnviarContatoPorEmail(contato); ViewData["MSG_S"] = Mensagem.MSG_S003; ViewData["MSG_E"] = ""; MvcCaptcha.ResetCaptcha("ExampleCaptcha"); return(View("Contato")); } else { ViewData["CONTATO"] = contato; return(View("Contato", contato)); } } catch (Exception) { ViewData["MSG_E"] = Mensagem.MSG_E000; } return(View("Contato")); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { if (!_authRepository.AlreadyExists(model.Email)) { // Try and send the confirmation email first. If that works, and the email is valid, then add it here. var result = _authRepository.Register(model.Email, model.Password); if (result.Success) { // Generate an email confirmation token for this account var token = AuthEncryption.RandomSalt(6); result = _authRepository.SetEmailConfirmationToken(model.Email, token); var secureUrl = Url.Action("ConfirmEmail", "Account", new { e = model.Email, c = token }, "https"); string mailBody = MailCommonStrings.RegisteredBody(secureUrl); Mailer.SendEmail_NoWait(model.Email, MailCommonStrings.RegisteredSubject, mailBody); _logger.Debug($"{model.Email} has successfully registered an account from {ClientIpAddress.GetIPAddress(Request)}"); MvcCaptcha.ResetCaptcha("regoCaptcha"); return(RedirectToAction("ConfirmationRequired")); } ModelState.AddModelError("", result.Message); } else { ModelState.AddModelError("", "An account with this email address already exists!"); } } // If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult Detail(Question model, HttpPostedFileBase fileInput) { if (ModelState.IsValid) { try { if (fileInput.ContentLength > 0) { string _fileName = Path.GetFileName(fileInput.FileName); bool exists = System.IO.Directory.Exists(Server.MapPath("~/FileAttach")); if (!exists) { Directory.CreateDirectory(Server.MapPath("~/FileAttach")); } string _path = Path.Combine(Server.MapPath("~/FileAttach"), _fileName); fileInput.SaveAs(_path); model.attachment = _fileName; } } catch (Exception ex) { } MvcCaptcha.ResetCaptcha("ExampleCaptcha"); model.createTime = DateTime.Now; _Service.Add(model); _Service.Save(); return(Content("<script language='javascript' type='text/javascript'>alert('Câu hỏi đã được gửi đi thành công!');window.location = '/hoi-dap';</script>")); } return(View(model)); }
public ActionResult SendFeedBack(FeedBackViewModel feedBackViewModel) { if (ModelState.IsValid) { var newFeedBack = new FeedBack(); newFeedBack.UpdateFeedBack(feedBackViewModel); _feedBackSerive.Create(newFeedBack); _feedBackSerive.Save(); ViewData["SuccessMsg"] = "Gửi phản hồi thành công"; string content = System.IO.File.ReadAllText(Server.MapPath("/Assets/client/templates/contact_template.html")); content = content.Replace("{{Name}}", feedBackViewModel.Name); content = content.Replace("{{Email}}", feedBackViewModel.Email); content = content.Replace("{{Message}}", feedBackViewModel.Message); var adminEmail = ConfigHelper.GetByKey("AdminEmail"); MailHelper.SendMail(adminEmail, "Thông tin liên hệ từ website", content); feedBackViewModel.Name = ""; feedBackViewModel.Email = ""; feedBackViewModel.Message = ""; } else { MvcCaptcha.ResetCaptcha("contactCaptcha"); } feedBackViewModel.ContactDetailViewModel = GetContactDetail(); return(View("Index", feedBackViewModel)); }
public ActionResult Contacto(Contacto cont) { bool prueba = MvcCaptcha.Validate("CaptchaCode", "Captcha", "Incorrect CAPTCHA code!"); MvcCaptcha.ResetCaptcha("Captcha"); return(View()); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { try { MvcCaptcha.ResetCaptcha("captcha"); if (!ModelState.IsValid) { return(View(model)); } // 這不會計算為帳戶鎖定的登入失敗 // 若要啟用密碼失敗來觸發帳戶鎖定,請變更為 shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout : false); _logger.Information("Login_Model:{0}", JsonConvert.SerializeObject(model)); _logger.Information("Login_Result:{0}", JsonConvert.SerializeObject(result)); switch (result) { case SignInStatus.Success: var user = _aspNetUsersService.GetUserModelByName(model.Username); if (user.IsStopAuthority.HasValue) { if (user.IsStopAuthority.Value) { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); ModelState.AddModelError("", "該帳號已停權!"); TempData["LoginResult"] = "該帳號已停權!"; return(View("Login", model)); } else { return(RedirectToLocal(returnUrl)); } } else { return(RedirectToLocal(returnUrl)); } case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "登入嘗試失敗。"); TempData["LoginResult"] = "嘗試登入失敗!"; return(View(model)); } } catch (Exception ex) { _logger.Information("Login_Error({0}) ", JsonConvert.SerializeObject(ex.Message)); throw ex; } }
public ActionResult Index(Clue obj, bool captchaValid, List <HttpPostedFileBase> Filename) { if (captchaValid) { if (ModelState.IsValid) { ClueMapDao clueMap = new ClueMapDao(); if (obj.ID == 0) { obj.Active = true; obj.CreateDate = DateTime.Now; obj.Keygen = Guid.NewGuid().ToString(); } obj.Complain_Channel_id = 1;//เรื่องร้องทุกข์ Online clueMap.Add(obj); clueMap.CommitChange(); SaveUtility.SaveClueFileUpload(Filename, "Clue", obj.Keygen); return(RedirectToAction("ClueModal", "Clue")); } } TempData.Clear(); ModelState.AddModelError("", "ข้อมูลไม่ถูกต้อง"); MvcCaptcha.ResetCaptcha("ClueCaptcha"); return(View(obj)); }
public ActionResult Contacts(Offer offer, HttpPostedFileBase image) { logger.Error("Oтправка формы Контакт админстратору "); if (ModelState.IsValid) { // TODO: Captcha validation failed, show error message if (image != null) { offer.ImageMimeType = image.ContentType; offer.ImageData = new byte[image.ContentLength]; image.InputStream.Read(offer.ImageData, 0, image.ContentLength); } offer.DateAdded = DateTime.Now; //[email protected] MailAddress fromMailAddress = new MailAddress("*****@*****.**", "UPR"); MailAddress toAddress = new MailAddress("*****@*****.**", "UPR"); // MailAddress toAddress = new MailAddress("*****@*****.**", "UPR"); using (MailMessage mailMessage = new MailMessage(fromMailAddress, toAddress)) using (SmtpClient smtpClient = new SmtpClient()) { mailMessage.Subject = "Форма обратная связь c сайта upr.kh.ua"; mailMessage.Body = "Имя: " + offer.Name.ToString() + "\r" + "Телефон: " + offer.Phone.ToString() + "\r" + "Почта: " + offer.Email.ToString() + "\r" + "Дата: " + offer.DateAdded.ToString() + "\r" + "Тема сообщения: " + offer.Title.ToString() + "\r" + "Сообщение: " + offer.Description.ToString() + "\r"; smtpClient.Host = "smtp.gmail.com"; smtpClient.Port = 587; smtpClient.EnableSsl = true; smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new NetworkCredential(fromMailAddress.Address, "1234567upr"); smtpClient.Send(mailMessage); } repository.SaveOffer(offer); TempData["message"] = string.Format("{0}, Ваше сообщение отправлено", offer.Name); MvcCaptcha.ResetCaptcha("SampleCaptcha"); return(RedirectToAction("Contacts")); } else { return(View(offer)); } // there is something wrong with the data values }
[SimpleCaptchaValidation("CaptchaCode", "registerCaptcha", "Mã xác nhận không đúng!")] // adđ sử dụng capcha(botdetect- Nugetpacket) https://captcha.com/asp.net-captcha.html // viết bất đồng bộ để check nhanh hơn public async Task <ActionResult> Register(RegisterViewModel registerViewModel) { if (ModelState.IsValid) { // check thông tin trùng var userCheckEmail = await _userManager.FindByEmailAsync(registerViewModel.Email); if (userCheckEmail != null) { ModelState.AddModelError("Email", "Email đã tồn tại"); return(View(registerViewModel)); } var userCheckName = await _userManager.FindByNameAsync(registerViewModel.UserName); if (userCheckName != null) { ModelState.AddModelError("UserName", "tài khoản đã tồn tại"); return(View(registerViewModel)); } // thêm mới tài khoản var user = new ApplicationUser() { UserName = registerViewModel.UserName, Email = registerViewModel.Email, EmailConfirmed = true, FullName = registerViewModel.FullName, Address = registerViewModel.Address }; await _userManager.CreateAsync(user, registerViewModel.Password); // add tài khoản vào db var addUser = await _userManager.FindByIdAsync(registerViewModel.Email); if (addUser != null) { await _userManager.AddToRolesAsync(addUser.Id, new string[] { "User" }); } // gửi mail báo thành công string content = System.IO.File.ReadAllText(Server.MapPath("/Assets/client/template/newUser.html")); content = content.Replace("{{UserName}}", addUser.FullName); // nhớ cấu hình lại CurrentLink trong appsetting var LinkWeb = ConfigHelper.GetByKey("CurrentLink"); content = content.Replace("{{Link}}", LinkWeb + "dang-nhap.html"); MailHelper.SendMail(addUser.Email, "đăng ký thành công", content); TempData["Ketqua"] = "Đăng ký thành công"; } else { MvcCaptcha.ResetCaptcha("registerCaptcha"); } return(View()); }
public ActionResult Registration() { MvcCaptcha.ResetCaptcha("SampleCaptcha"); ViewData["cities"] = db.City.Select(x => new SelectListItem() { Text = x.Name, Value = x.CCode.ToString() }).ToList(); return(View()); }
public static MvcCaptcha GetLoginCaptcha() { MvcCaptcha loginCaptcha = new MvcCaptcha("LoginCaptcha"); loginCaptcha.UserInputID = "CaptchaCode"; loginCaptcha.ImageSize = new System.Drawing.Size(255, 50); return(loginCaptcha); }
public virtual ActionResult Contact(string model) { if (ModelState.IsValid) { // You should call ResetCaptcha as demonstrated in the following example. MvcCaptcha.ResetCaptcha("SampleCaptcha"); } return(Json(model)); }
public static MvcCaptcha GetCaptcha(string captchaName) { MvcCaptcha captcha = new MvcCaptcha(captchaName); captcha.ImageStyle = BotDetect.ImageStyle.Graffiti; captcha.ImageSize = new System.Drawing.Size(75, 30); captcha.CodeLength = 5; return(captcha); }
public static MvcCaptcha GetCustomCaptcha() { // create the captcha object instance MvcCaptcha customCaptcha = new MvcCaptcha("CustomCaptcha") { // set up client-side processing of the Captcha code input textbox (found on the Login view) UserInputID = "captchaTextBox" }; return(customCaptcha); }
public async Task <IActionResult> JobOpportunities() { ViewBag.SlidePath = _configuration["header-slide:job"]; ViewBag.MobileSlidePath = _configuration["header-slide:job_mobile"]; MvcCaptcha mvcCaptcha = new MvcCaptcha("FormCaptcha"); mvcCaptcha.UserInputID = "CaptchaCode"; await FillLists(); return(View()); }
/// <summary> /// 获取DotDetect验证码对象 /// </summary> /// <param name="captChaId">验证码Id,用于标识一个验证码</param> /// <param name="inputId">验证码输入框的id</param> /// <param name="width">验证码图片宽度</param> /// <param name="height">验证码图片高度</param> /// <returns></returns> public static MvcCaptcha GetCaptcha(string captChaId, string inputId, int width = 250, int height = 50) { // create the control instance MvcCaptcha mvcCaptcha = new MvcCaptcha(captChaId); //captChaId:用于标识一个验证码 // set up client-side processing of the Captcha code input textbox mvcCaptcha.UserInputID = inputId; //验证码输入框的id mvcCaptcha.HelpLinkEnabled = false; //页面不显示dot detect帮助链接 mvcCaptcha.ImageSize = new Size(width, height); return(mvcCaptcha); }
public static MvcCaptcha GetRegistrationCaptcha() { // create the control instance MvcCaptcha registrationCaptcha = new MvcCaptcha("RegistrationCaptcha"); registrationCaptcha.UserInputClientID = "CaptchaCode"; // all Captcha settings have to be saved before rendering registrationCaptcha.SaveSettings(); return(registrationCaptcha); }
public ActionResult Login(LoginViewModel model, string returnUrl) { try { if (ModelState.IsValid) { ApplicationUser user = UserManager.Instance.UserManagerment.Find(model.UserName, model.Password); if (user != null) { if (!user.Status) { ViewData["ErrorLogin"] = "******"; } else if (user.Group != 1) { ViewData["ErrorLogin"] = "******"; } else { IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication; authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity identity = UserManager.Instance.UserManagerment.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); AuthenticationProperties props = new AuthenticationProperties(); authenticationManager.SignIn(props, identity); return(RedirectToLocal(returnUrl)); } } else { ViewData["ErrorLogin"] = "******"; } } MvcCaptcha loginCaptCha = new MvcCaptcha("LoginCaptCha"); loginCaptCha.UserInputID = "CaptchaCode"; model.LoginCaptCha = loginCaptCha; loginCaptCha.AutoClearInput = true; loginCaptCha.AutoUppercaseInput = true; ViewBag.ReturnUrl = returnUrl; return(View(model)); } catch (Exception ex) { LogError(ex); MvcCaptcha loginCaptCha = new MvcCaptcha("LoginCaptCha"); loginCaptCha.UserInputID = "CaptchaCode"; model.LoginCaptCha = loginCaptCha; loginCaptCha.AutoClearInput = true; loginCaptCha.AutoUppercaseInput = true; ViewBag.ReturnUrl = returnUrl; ViewData["ErrorLogin"] = "******"; return(View(model)); } }
//[CaptchaValidation("CaptchaCode", "UserRegisterCaptcha","Incorrect CAPTCHA code!")] public async Task <IActionResult> Register(RegisterViewModel model) { MvcCaptcha mvcCaptcha = new MvcCaptcha("UserRegisterCaptcha"); string validatingInstanceId = mvcCaptcha.WebCaptcha.ValidatingInstanceId; if (mvcCaptcha.Validate(model.CaptchaCode, validatingInstanceId)) { if (ModelState.IsValid) { UserDTO userDto = new UserDTO { Email = model.Email, Year = model.Year, Password = model.Password, UserName = model.Email }; MvcCaptcha.ResetCaptcha("UserRegisterCaptcha"); OperationDetails operationDetails = await userService.Create(userDto); if (operationDetails.Succeeded) { var claims = await userService.Authenticate(userDto); string token = await GenerateJwtToken(claims); Response.Cookies.Append("Authorization", "Bearer " + token, new CookieOptions() { IsEssential = true }); return(RedirectToAction("Index", "Home")); } else { ModelState.AddModelError(operationDetails.Property, operationDetails.Message); } } else { MvcCaptcha.ResetCaptcha("UserRegisterCaptcha"); ModelState.AddModelError("", "Wrong email or password"); } } else { MvcCaptcha.ResetCaptcha("UserRegisterCaptcha"); ModelState.AddModelError("CaptchaCode", "Incorrect!"); } return(View(model)); }
public static MvcCaptcha GetRegistrationCaptcha() { // create the control instance MvcCaptcha registrationCaptcha = new MvcCaptcha("RegistrationCaptcha"); // set up client-side processing of the Captcha code input textbox registrationCaptcha.UserInputID = "CaptchaCode"; // Captcha settings registrationCaptcha.ImageSize = new System.Drawing.Size(255, 50); return(registrationCaptcha); }
public ActionResult Login(string returnUrl) { var model = new LoginViewModel(); MvcCaptcha loginCaptCha = new MvcCaptcha("LoginCaptCha"); loginCaptCha.Reset(); loginCaptCha.UserInputID = "CaptchaCode"; loginCaptCha.AutoClearInput = true; loginCaptCha.AutoUppercaseInput = true; model.LoginCaptCha = loginCaptCha; ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public static MvcCaptcha GetRegistrationCaptcha() { // create the control instance MvcCaptcha registrationCaptcha = new MvcCaptcha("RegistrationCaptcha"); // set up client-side processing of the Captcha code input textbox registrationCaptcha.UserInputID = "CaptchaCode"; // Captcha settings registrationCaptcha.ImageSize = new System.Drawing.Size(255, 50); return registrationCaptcha; }
public async Task <IActionResult> Index(int chinhanhid, string cmnd, string makhachhang, bool tochuc) { //_IChiNhanhService.get(); //ViewBag.CategoryList = _IChiNhanhService.cateList; string userInput = HttpContext.Request.Form["CaptchaCode"]; // init mvcCaptcha instance with captchaId MvcCaptcha mvcCaptcha = new MvcCaptcha("registerCapcha"); if (mvcCaptcha.Validate(userInput)) { using (var context = new DataContext()) { IEnumerable <BangKeModel> categories = await context.ChiTietTKCKH.Select(x => new BangKeModel { id = x.Id, ChiNhanhID = x.ChiNhanhID, CMND = x.CMND, MaKhachHang = x.MaKhachHang, ToChuc = x.ToChuc, }).Where(p => p.ChiNhanhID == chinhanhid && p.CMND == cmnd.Trim() && p.MaKhachHang == makhachhang.Trim().ToUpper() && p.ToChuc == tochuc).ToListAsync();// line 2; if (categories.Count() > 0) { HttpContext.Session.SetString(CommonConstants.USER_SESSION, bussiness.mahoamd5(cmnd.Trim())); try { ThongKe f = await context.ThongKe.FirstOrDefaultAsync(e => e.Id == 1); f.XemTietKiem++; context.SaveChanges(); } catch { } return(RedirectToAction("BangKe", "Home", new { id1 = bussiness.mahoamd5(chinhanhid.ToString()), id2 = bussiness.mahoamd5(cmnd.Trim()), id3 = bussiness.mahoamd5(makhachhang.Trim().ToUpper()), id4 = bussiness.mahoamd5(tochuc.ToString()) })); // _bangKeService.KhachHang(bussiness.mahoamd5(chinhanhid.ToString()), bussiness.cmnd = bussiness.mahoamd5(cmnd), bussiness.mahoamd5(makhachhang.ToUpper()), tochuc); } else { ModelState.AddModelError("MaKhachHang", "Không tìm thấy dữ liệu!"); return(View()); } } } else { ModelState.AddModelError("CaptchaCode", "Mã xác nhận không đúng!"); return(View()); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // This needs to be tested to see if it actually encodes the data for preventing XSS attacks. model.Email = Encoder.HtmlEncode(model.Email); model.Password = Encoder.HtmlEncode(model.Password); // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false); if (MvcCaptcha.IsCaptchaSolved("CustomCaptcha")) { // Use this to reset the captcha after the submit button has been pressed... This may need to be moved to the SignInStatus.Success case. MvcCaptcha.ResetCaptcha("CustomCaptcha"); switch (result) { case SignInStatus.Success: return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } } else { // Use this to reset the captcha after the submit button has been pressed... This may need to be moved to the SignInStatus.Success case. MvcCaptcha.ResetCaptcha("CustomCaptcha"); ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { var dao = new UserDAO(); if (dao.CheckUserName(model.UserName)) //nếu check user từ model truyền vào trùng với DAO thì xuất mã lỗi { ModelState.AddModelError("", "Tên đăng nhập đã tồn tại!"); } else if (dao.CheckEmail(model.Email)) //nếu check Email từ model truyền vào trùng với DAO thì xuất mã lỗi { ModelState.AddModelError("", "Email đã tồn tại!"); } else //không có lỗi thì ta tạo tài khoản { var user = new User(); //tạo đối tượng và truyền từ model vào EF user.UserName = model.UserName; user.Name = model.Name; user.Password = model.Password; user.Phone = model.Phone; user.Email = model.Email; user.Address = model.Address; user.CreatedDate = DateTime.Now; user.Status = true; if (!string.IsNullOrEmpty(model.ProvinceID)) //model khác rỗng { user.ProvinceID = int.Parse(model.ProvinceID); } if (!string.IsNullOrEmpty(model.DistrictID)) { user.DistrictID = int.Parse(model.DistrictID); } var result = dao.Insert(user); //insert user if (result > 0) //nếu > 0 thì có tài khoản { ViewBag.Success = "Đăng kí thành công :) "; model = new RegisterModel(); //reset toàn bộ model lại cho lần tạo tài khoản tiếp theo } else { ModelState.AddModelError("", "Đăng kí không thành công :( "); MvcCaptcha.ResetCaptcha("registerCapcha"); } } } return(View(model)); }
public static MvcCaptcha GetRegistrationCaptcha() { // create the control instance MvcCaptcha registrationCaptcha = new MvcCaptcha("RegistrationCaptcha"); registrationCaptcha.UserInputClientID = "CaptchaCode"; // all Captcha properties are set in this event handler registrationCaptcha.InitializedCaptchaControl += new EventHandler<InitializedCaptchaControlEventArgs>( RegistrationCaptcha_InitializedCaptchaControl); // all Captcha settings have to be saved before rendering registrationCaptcha.SaveSettings(); return registrationCaptcha; }
public ActionResult form1(Form1VM model) { if (!ModelState.IsValid) { // TODO: Captcha validation failed, show error message return(View(model)); } else { // TODO: captcha validation succeeded; execute the protected action // Reset the captcha if your app's workflow continues with the same view MvcCaptcha.ResetCaptcha("ExampleCaptcha"); return(Content("captcha is Correct")); } }
public SharedModel() { myCaptcha = new MvcCaptcha("SampleCaptcha"); myCaptcha.UserInputClientID = "CapchaCode"; }