ASP.Net MVC Validation (server side) - ajax

asp.net mvc server side validation when the javascript is disabled in the browser? i used "remote" in my modal class it validates only when the javascript is enabled it doesnt validate when the javascript is disabled.
Scenario for my problem is i have a table in my db with a column "code" with the datatype varchar. any one inserts the data they must insert the unique code.
Please do help me out

I would suggest to forget about remote because if you are using code first entity framework, you can't have more that one unique column in your table. I would just write code for it like this:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Insert a new user into the database
using (UsersContext db = new UsersContext())
{
UserProfile email = db.UserProfiles.FirstOrDefault(u => u.Email.ToLower() == model.Email.ToLower());
try
{
// Check if email already exists
if (email == null)
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email });
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("Email", "Email address already exists. Please enter a different email address.");
}
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
}
Replace the email with the property you want to validate. At post, this will compare with entries with what already exists in your database, and depending on results, it will give you feedback. Throws exception if such data exists.

Related

how i can Show error for unique fields in asp.net core

I have a problem In association with validation property! I use .net core 2.1. I checked unique fields in OnModelCreating method in DbContext class and it's working fine. now I want to display an error message if the user enters the same BirthCertificate value (already exists in the database) in the input field like that Display & Required & MaxLength & ... attributes and send (bind) it to ModelState to check it. i also use jquery.validate.js in the client and show all errors and it's working fine. how I should do this:
Public Class Person
{
[Display(Name = "Enter BirthCertificate")]
[Required(ErrorMessage = "Please enter {0}")]
[MaxLength(10, ErrorMessage = "Max lenght is {0}")]
public string BirthCertificate { get; set; }
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<DomainClasses.Person.Person>(entity =>
{
entity.HasIndex(e => e.BirthCertificate).IsUnique(); // it's working fine
});
}
thanks
You can use either one of these.
1) Create new unique key for BirthCertificate in SQL Server. Use catch (Exception ex) and return to ajax to show error.
2) Do checking code
if (db.Person.Where(x => x.BirthCertificate.Contains(birthcert)).Any())
{
//return to ajax to show error
}

Background Registration MVC3

Working on an MVC4 Application where users first fill in a form as the starting point. With this form there is a field to provide user email and a unique 9 digit number and other details. What I want to achieve is after submitting this form I want the user to be silently registered using the unique 9 digit number as username, and an auto-generated password hashed and saved as password in the membership(extended simplemembership) database. An email with password will be sent to the user afterwards. I will be grateful for any hints or help in this regards.
After the form is filled, I make the following redirection
return RedirectToAction("AutoRegister", new RouteValueDictionary(new { controller = "Account", action = "AutoRegister", Uname= ViewBag.Uname, Uemail = ViewBag.Uemail }));
and I have the following code in Account Controller
[AllowAnonymous]
public ActionResult AutoRegister()
{
return View();
}
[AllowAnonymous]
[HttpPost]
public ActionResult AutoRegister(RegisterModel model,string Uname, string Uemail)
{
//if (ModelState.IsValid)
if(Uemail!=null && Uname!=null)
{
string Upass = Membership.GeneratePassword(12, 1);
model.Email = Uemail;
model.UserName = Uname;
model.Password = Upass;
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: false, providerUserKey: null, status: out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
return RedirectToAction("Welcome", "OnlineApplication");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
I have also set the RouteConfig to accept the url. When I fill the form it redirects allright to a page with the url parameters populated but nothing happens. The user is not created. As for emailing of password I can fix that with no problems.
Could anyone assist on how I can commit the new user details in database

ASP.net MVC 3 customizing Html.ValidationMessageFor based on model logic

I've been reading over several of the questions similar to this, dealing with customizing the #Html.ValidationMessageFor but none of them touched on what I'm looking to do.
The current form I'm working on is editing a user in a database. Within this form I need to check that the email being entered is not already used for another user. I have the logic, but what I don't have is the custom validation message to appear on the page if they use an already in-use email.
Controller code:
[HttpPost]
public ActionResult EditUser(int id, EditUserModel model)
{
if (ModelState.IsValid)
{
tbl_Users editedUser = tblUsers.EditUser(id, model, HttpContext.User.Identity.Name);
tblHSDA.EditHSDAS(id, editedUser, model.hsdas, HttpContext.User.Identity.Name);
return Redirect("~/UserManage/ListActiveUsers");
}
if (tblUsers.ValidateEmailInUse(model.Email))
{
// change validation message and return View(model);
}
tbl_Users tbl_users = db.tbl_Users.SingleOrDefault(item => item.User_id == id);
ViewBag.hsdas = tblHSDA.GetHSDANameAlpha();
ViewBag.Username = tbl_users.Username;
return View(model);
}
Is this something done at the Controller level?
as per your logic the email check part will never execute if the user fills in the form correctly and provides a duplicate email
what you can do is change the ActionResult like
[HttpPost]
public ActionResult EditUser(int id, EditUserModel model)
{
if (ModelState.IsValid)
{
if(!CheckEmail(model.Email)){
tbl_Users editedUser = tblUsers.EditUser(id, model, HttpContext.User.Identity.Name);
tblHSDA.EditHSDAS(id, editedUser, model.hsdas, HttpContext.User.Identity.Name);
return Redirect("~/UserManage/ListActiveUsers");
}else{
ModelState.AddModelError("Email","Email provided is already in use...")
}
}
tbl_Users tbl_users = db.tbl_Users.SingleOrDefault(item => item.User_id == id);
ViewBag.hsdas = tblHSDA.GetHSDANameAlpha();
ViewBag.Username = tbl_users.Username;
return View(model);
}
private bool CheckEmail(string email){
//email check logic
// return true or false
}
also have a look at http://msdn.microsoft.com/en-us/library/gg508808%28v=vs.98%29.aspx

Remote validation on MVC3 is trigger on keypress/keyrelease instead on lostfocus

I'm trying Remote validation on MVC3 for an user name input text on a register form, everything work ok except that I'm expecting the remote validation trigger when the input lost focus but it is triggering on every key-press or key-up that is written in the input, resulting in many request to the action validation many as every character you write.
There are any way to change this behaviour using the build in unobtrusive javascript.
This is how my property model look like:
[Required]
[Display(Name = "User Name")]
[Remote("ValidateUniqueUserName", "Account")]
public string UserName { get; set; }
this is how the controller looklike:
public JsonResult ValidateUniqueUserName(string username)
{
if (string.IsNullOrEmpty(username))
{
return Json("User Name is required", JsonRequestBehavior.AllowGet);
}
var result = _membershipApplicationService.IsUserNameAvalible(username);
if (!result)
{
return Json("User Name is already taken, please try another one", JsonRequestBehavior.AllowGet);
}
return Json(true, JsonRequestBehavior.AllowGet);
}
And the register form is rendered using a #Html.Partial
thanks.

WebSecurity vs FormsAuthentication in ASP.NET MVC4

I guess I am trying to mix two providers in project but I am looking to use websecurity in conjunction to my forms authentication. I need websecurity for OAUTH authentication using Facebook, and google.
The error that I am getting when I try to login using facebook is
To call this method, the Membership.Provider property must be an instance of ExtendedMembershipProvider.
Here are the code samples. How can I use both?
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return RedirectToLocal(returnUrl);
}
if (User.Identity.IsAuthenticated)
{
// If the current user is logged in add the new account
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
return RedirectToLocal(returnUrl);
}
else
{
// User is new, ask for their desired membership name
string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
}
}
and
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Could possibly be related to the same issue as me MVC4 ExtendedMembershipProvider and entityframework
.. I removed the universal providers nuget package and this particular error dissappeared.
Also this "very recent" article by Jon Galloway may help.
If you are using Visual Studio, you might want to save yourself all this effort. The MVC 4 Internet template comes with four external identity providers out of the box. I have tested them and Google Accounts, Microsoft account, Facebook login, and Twitter login all work fine, with zero lines of code!
I think the same is provided with the Web Form template too.
More info at http://blogs.msdn.com/b/webdev/archive/2012/08/15/oauth-openid-support-for-webforms-mvc-and-webpages.aspx.
You can use an implementation of ExtendedMembershipProvider. For ex: the built-in SimpleMembershipProvider.
Every ExtendedMembershipProvider IS A MembershipProvider .
Read more at Jon Galloway's Blog.

Resources