remote validation in mvc affected edit - asp.net-mvc

I was trying to validate the user name through remote validation in client side and it's working fine in while adding the duplicate field in create Module but now it is not allowing me to edit the record using same name it's showing me the same error which I defined for create. I tried all the possible ways but not succeeded please help me. I have followed these link but it's not working in either way.
http://stackoverflow.com/questions/4778151/asp-net-mvc-3-remote-validation-to-allow-original-value
http://stackoverflow.com/questions/6407096/asp-net-mvc-3-remote-attribute-passing-3-fields
here is my code what i have tried so far .please help experts.
[Required]
[Remote("IsUserAvailable", "User", HttpMethod = "Post", ErrorMessage = "User already exist.", AdditionalFields = "InitialUserName")]
[RegularExpression(#"^(?![\W_]+$)(?!\d+$)[a-zA-Z0-9 ]+$", ErrorMessage = "Invalid UserName ")]
public string UserName { get; set; }
[HttpPost]
public JsonResult IsUserAvailable([Bind(Prefix = "User.UserName")]string UserName, string initialUserName)
{
var result = uDbContext.Users.FirstOrDefault(a => a.UserName == UserName);
if (result == null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json(JsonRequestBehavior.AllowGet);
}
#model User.ViewModel.ViewModelUser
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(m => m.User.UserId)
#Html.LabelFor(m.User.UserName)
#Html.TextBoxFor(m => m.User.UserName)
#Html.ValidationMessageFor(m.User.UserName)
#Html.Hidden("initialUserName", Model.User)
</div>
</div>
}
Please help experts to complete my assignment.

User appears to be a complex object so
#Html.Hidden("initialUserName", Model.User)
is likely to generate something like
<input type="hidden" name="initialUserName" value="YourAssemly.User" ... />
which is not going to help with validation.
You could ignore the validation by sending back the original name using
#Html.Hidden("InitialUserName", Model.User.UserName)
#Html.Hidden("User.InitialUserName", Model.User.UserName)
and then compare the values in the controller using
public JsonResult IsUserAvailable([Bind(Prefix = "User.UserName")]string UserName, string initialUserName)
public JsonResult IsUserAvailable([Bind(Prefix = "User.UserName")]string UserName, [Bind(Prefix = "User.InitialUserName")]string initialUserName)
{
if (UserName == initialUserName)
{
// Nothing has changed so signal its valid
return Json(true, JsonRequestBehavior.AllowGet);
}
// Check if the user name already exists
var result = uDbContext.Users.FirstOrDefault(a => a.UserName == UserName);
return Json(result == null, JsonRequestBehavior.AllowGet);
}
Side note: jquery remote validation is a GET call so the [HttpPost] attribute is not necessary
Edit
After debugging both the jquery-validate.js and jquery-validate-unobtrusive.js files, it turns out that the name attribute of any AdditionalFields must include the same prefix as the property being validated, and that the [Bind(Prefix="..")] attribute is then also required on those parameters in the method (refer amendments above)
An alternative might to create a simple class to post back to, for example
public class ValidateUserNameVM
{
public string UserName { get; set; }
public string InitialUserName { get; set; }
}
and
public JsonResult IsUserAvailable([Bind(Prefix = "User")]ValidateUserNameVM model)
{
if (model.UserName == model.InitialUserName)
....

Your validation function is incomplete. Put a [Required] attribute on the UserName property of your model and try this:
public JsonResult IsUserAvailable(string userName, string initialUserName)
{
if (userName.Trim().ToLower() != (initialUserName ?? "").Trim().ToLower())
{
var result = YourMethodToCheckTheDatabaseForUsernameIsAvailable(userName);
return Json(result, JsonRequestBehavior.AllowGet);
}
return Json(true, JsonRequestBehavior.AllowGet);
}

For Who Get Null in the second paramter this simple idea could help
public JsonResult IsUserNameAvailable(string Name, string EditNameIssue)
{//it will return true if match found elese it will return false. so i add !
if (Name == EditNameIssue)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
return Json(!db.Employees.Any(e => e.Name == Name), JsonRequestBehavior.AllowGet);
}
}
Go to The Class and add string EditNameIssue to the class so it could be sent to the controller
[MetadataType(typeof(EmployeeMetaData))]
public partial class Employee
{
public string EditNameIssue { get; set; }
}
And Edit the Remote attribute to send this addtional property
[Remote("IsUserNameAvailable","Employees",ErrorMessage ="User Name Already Taken",AdditionalFields = "EditNameIssue")]
public string Name { get; set; }
This Logic may help if you add a name to edit textbox that is already taken
public JsonResult IsUserNameAvailable(string Name, string EditNameIssue)
{//it will return true if match found elese it will return false. so i add !
//Edit Request
if (Name == EditNameIssue)
{
//this mean he didn't change the name
return Json(true, JsonRequestBehavior.AllowGet);
}
else if (Name != EditNameIssue)
{
//if he change the name in the edit go and check if the new name exist
//note if he modify and reenter it origin name it will be also erro he has to reload
return Json(!db.Employees.Any(e => e.Name == Name), JsonRequestBehavior.AllowGet);
}
else if (string.IsNullOrEmpty(EditNameIssue))
{//this mean you came from create request as there is no EditNameIssue in this view
return Json(!db.Employees.Any(e => e.Name == Name), JsonRequestBehavior.AllowGet);
}
else
{//just for the completeness
return Json(false, JsonRequestBehavior.AllowGet);
}
}

Related

Model View Remote Validation

I am doing a remote validation using Remote attribute in my MVC model, please find the code below:
[Required]
[System.Web.Mvc.Remote("IsEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "The Email Already Exists")]
In the controller action method I use the user input of email as a parameter and check with the db, please find the code below:
public JsonResult IsEmailExist(string emailAddress)
{
using (var db = new YouTubeNZ())
{
var isExist = !db.Users.Any(X => X.EmailAddress == emailAddress);
return Json(isExist, JsonRequestBehavior.AllowGet);
}
}
But during run time the parameter in the action method is "Null" when the value should be the user input email address and it is not getting validated for existing email.
Make sure you decorate your action method with HttpPost attr, and your property name matches the method parameter (i.e: EmailAddress):
[HttpPost]
public JsonResult IsEmailExist(string emailAddress)
{
using (var db = new YouTubeNZ())
{
var isExist = !db.Users.Any(X => X.EmailAddress == emailAddress);
return Json(isExist, JsonRequestBehavior.AllowGet);
}
}
Please make sure the following.
Your model property should be like
[Required]
[System.Web.Mvc.Remote("IsEmailExist", "Account", ErrorMessage = "The Email Already Exists")]
public string EmailAddress { get; set; }
Also change your AccountsController action method to
public ActionResult IsEmailExist(string emailAddress)
{
using (var db = new YouTubeNZ())
{
bool isExist = !db.Users.Any(X => X.EmailAddress == emailAddress);
return Json(isExist, JsonRequestBehavior.AllowGet);
}
}
Your Model should be like this
[Required]
[Remote("IsEmailExist","Account",ErrorMessage="This Email is already exists")]
public string EmailAddress{get;set;}
And Controller should be like this
public JsonResult IsEmailExist(string emailAddress)
{
return Json(isExist(emailAddress),JsonRequestBehavior.AllowGet);
}
private bool isExist(string emailAddress)
{
using (var db = new YouTubeNZ())
{
return !db.Users.Any(X => X.EmailAddress == emailAddress);
}
}

Remote Validation in mvc not working

I am trying to use Remote validation in my application to check already exists record.
Here:
[Required(ErrorMessage = "*")]
public Nullable<long> fk_Store_ID { get; set; }
[System.Web.Mvc.Remote("doesGround", "User", HttpMethod = "POST", ErrorMessage = "Ground Level is already exists for this store.", AdditionalFields = "fk_Store_ID")]
[DefaultValue(false)]
public bool MembershipGroundLevel { get; set; }
and my controller action:
[HttpPost]
public JsonResult doesGround(bool MembershipGroundLevel, long? fk_Store_ID)
{
Int64 store_id = Convert.ToInt64(fk_Store_ID);
var count = db.tbl_Membership
.Where(o => o.fk_Store_ID == store_id && o.MembershipGroundLevel == true && o.isVisible == true).Count();
return count >= 1 ? Json(false, JsonRequestBehavior.AllowGet) : Json(true, JsonRequestBehavior.AllowGet);
}
Here I am getting NULL value for both. If I change datatype to bool and long respectively. I am getting internal server 500 error
I think your action doesGround definition is wrong, please try following one
public JsonResult doesGround(bool MembershipGroundLevel, long? fk_Store_ID)
It is also good to ask if your validation UserController controller is in Area, it yes, you need to specify area name in RemoteAttribute deffinition by RoutData property.

ASP.NET MVC Remote attribute method parameter always passing null

I have this AdvertiserNameAvailable method that is being used by Remote validation attribute.
The problem is that the AdvertiserNameAvailable is being called without passing the input value to the method Name parameter. When I enter in debug into the method, I see that the Name parameter is always null.
public JsonResult AdvertiserNameAvailable(string Name)
{
return Json("Some custom error message", JsonRequestBehavior.AllowGet);
}
public class AdvertiserAccount
{
[Required]
[Remote("AdvertiserNameAvailable", "Accounts")]
public string Name
{
get;
set;
}
}
Had to add [Bind(Prefix = "account.Name")]
public ActionResult AdvertiserNameAvailable([Bind(Prefix = "account.Name")] String name)
{
if(name == "Q")
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
To find out your prefix, right click and do inspect element on the input that you are trying to validate. Look for the name attribute:
<input ... id="account_Name" name="account.Name" type="text" value="">
[HttpPost]
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public ActionResult AdvertiserNameAvailable(string Name)
{
bool isNameAvailable = CheckName(Name); //validate Name and return true of false
return Json(isNameAvailable );
}
public class AdvertiserAccount
{
[Required]
[Remote("AdvertiserNameAvailable", "Accounts", HttpMethod="Post", ErrorMessage = "Some custom error message.")]
public string Name
{
get;
set;
}
}
Also to note:
The OutputCacheAttribute attribute is required in order to prevent
ASP.NET MVC from caching the results of the validation methods.
So use [OutputCache(Location = OutputCacheLocation.None, NoStore = true)] on your controller action.

Remote Validation seems buggy

imagine this situation:
SetUp
in the default MVC3 project, create a new complex type in the AccountModels.cs
public class GlobalAccount
{
public GlobalAccount()
{
this.LogOn = new LogOnModel();
this.Register = new RegisterModel();
}
public LogOnModel LogOn { get; set; }
public RegisterModel Register { get; set; }
}
In the RegisterModel change the UserName to:
[Required]
[Remote("UserNameExists", "Validation", "", ErrorMessage = "Username is already taken.")]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed.")]
[Display(Name = "Username (spaces will be stripped, must be at least 6 characters long)")]
public string UserName { get; set; }
The UserNameExists method in a Validation controller is as follow:
public class ValidationController : Controller
{
public JsonResult UserNameExists(string UserName)
{
string user = null;
if (!String.IsNullOrWhiteSpace(UserName) && UserName.Length >= 6)
user = UserName == "abcdef" ? "ok" : null;
return user == null ?
Json(true, JsonRequestBehavior.AllowGet) :
Json(string.Format("{0} is not available.", UserName), JsonRequestBehavior.AllowGet);
}
}
Now in the Register View, use the GlobalAccount Model instead of the RegisterModel
the username input box will be like:
#model Your.NameSpace.Models.GlobalAccount
and
<div class="field fade-label">
#Html.LabelFor(model => model.Register.UserName, new { #class = "text" })
#Html.TextBoxFor(model => model.Register.UserName, new { spellcheck = "false", size = "30" })
</div>
this will result in something like this, in the HTML
<div class="field fade-label">
<label class="text" for="Register_UserName"><span>Username (spaces will be stripped, must be at least 6 characters long)</span></label>
<input data-val="true" data-val-regex="White space is not allowed." data-val-regex-pattern="(\S)+" data-val-remote="Username is already taken." data-val-remote-additionalfields="*.UserName" data-val-remote-url="/beta/Validation/UserNameExists" data-val-required="The Username (spaces will be stripped, must be at least 6 characters long) field is required." id="Register_UserName" name="Register.UserName" size="30" spellcheck="false" type="text" value="">
</div>
Debug
If you use FireBug to check what's going on ... the Remote Validation is sending the attribute name instead of the attribute id to the Validation method (the UserNameExists one) as:
Register.UserName instead of Register_UserName
So I can't fetch this value ... ever :(
Is this really a bug or is something that someone already found and I couldn't get from Googling it?
Here is a simple image of the actual problem:
How about:
public ActionResult UserNameExists(
[Bind(Include = "UserName")]RegisterModel register
)
{
string user = null;
if (!String.IsNullOrWhiteSpace(register.UserName) && register.UserName.Length >= 6)
user = register.UserName == "abcdef" ? "ok" : null;
return user == null ?
Json(true, JsonRequestBehavior.AllowGet) :
Json(string.Format("{0} is not available.", register.UserName), JsonRequestBehavior.AllowGet);
}
Another possibility is to define a special view model:
public class UserNameExistsViewModel
{
public string UserName { get; set; }
}
and then:
public ActionResult UserNameExists(UserNameExistsViewModel register)
{
string user = null;
if (!String.IsNullOrWhiteSpace(register.UserName) && register.UserName.Length >= 6)
user = register.UserName == "abcdef" ? "ok" : null;
return user == null ?
Json(true, JsonRequestBehavior.AllowGet) :
Json(string.Format("{0} is not available.", register.UserName), JsonRequestBehavior.AllowGet);
}
What is annoying is that the following doesn't work:
public ActionResult UserNameExists(
[Bind(Prefix = "Register")]string UserName
)
Go figure :-) I would probably go with a custom view model. It looks cleanest.
I know this is marked as answered, but as I'm having the same issue I thought I would contribute another variation that is working for me.
The class in my case is "Food" and the field I'm attempting to remote validate is "Name". The textbox is being created by an EditorFor control:
#Html.EditorFor(model => model.Name)
Remote validation is set on the Food class field:
[Remote("FoodNameExists")]
public string Name { get; set; }
And this calls a method:
public ActionResult FoodNameExists(string Name) {
As per the original question, rather than this being passed to the FoodNameExists method as "Name", or even "Food_Name", which is the Id value created by the EditorFor helper, it is getting passed as the name attribute which is "Food.Name"... which of course is not something I can set as an input parameter.
So, my hack is simply to ignore the input parameters and look in the QueryString:
var name = Request.QueryString["Food.Name"];
...this returns the correct value, which I validate against and I'm off to the races.
This is the simpliest way I found to do it, just adding data-val-- attributes in HtmlAttributes of DropDownListFor, inside the view. The following method works with RemoteValidation too, if you do not need remote validation, simply remove the elements containing data-val-remote-*:
#Html.DropDownListFor(m => m.yourlistID, (IEnumerable<SelectListItem>)ViewBag.YourListID, String.Empty,
new Dictionary<string, object>() { { "data-val", "true" },
{ "data-val-remote-url", "/Validation/yourremoteval" },
{ "data-val-remote-type", "POST" }, { "data-val-remote-additionalfield", "youradditionalfieldtovalidate" } })
I hope it may help. Best Regards!

Custom validation error not displayed

I have an MVC 3 application and am trying to display a custom validation error. The normal validation errors that are generated by the model, i.e. Required, are displayed on the page. Now I am checking if a user exists and if so, adding a error message:
if (userExists)
ModelState.AddModelError("UserName", UserManagementResources.UserAlreadyExistsText);
return View(model);
On the view I have a validation summary and a Html.ValidationMessage("UserName"), but neither one is displaying the error. I have used this successfully on other pages. The only difference with this page I can see is, that it uses the RequiredIf validator scripts.
http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx
Any ideas how to solve this problem are appreciated. Thanks.
Edit
I am returning the validation message through the Remote validation. If I look what the network is doing, it's returning the error message, but it is still not displayed on the view.
[Required]
[DataType(DataType.EmailAddress)]
[Remote("IsUserAvailable", "Validation", ErrorMessage = "Ein Benutzer mit dieser Email existiert bereits.")]
[Display(Name = Resources.EmailText, ResourceType = typeof(Resources))]
public string Email
{
get { return User.Email; }
set { User.Email = value; }
}
The View:
#Html.LabelFor(u => u.Email, Resources.Email + " (Login) *")
#Html.EditorFor(u => u.Email)
#Html.ValidationMessageFor(u => u.Email)
<br clear="all" />
The Remote Validation Controller:
public class ValidationController : Controller
{
public JsonResult IsUserAvailable(string Email)
{
bool userExists;
using (var userModel = new UserManagementModel())
{
userExists = userModel.UserExists(Email);
}
if(userExists)
return Json(UserManagementResources.UserAlreadyExists, JsonRequestBehavior.AllowGet);
else
return Json(true, JsonRequestBehavior.AllowGet);
}
}
Why don't you use the Remote validation for this?
Why posting back just to check if user exists?
example:
public class RegisterModel
{
[Required]
[Remote("UserNameExists", "Validation", "", ErrorMessage = "Username is already taken.")]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed.")]
[Display(Name = "Username")]
public string UserName { get; set; }
}
and create a Validation Controller having the UserNameExists method like
public JsonResult UserNameExists(string UserName)
{
var user = _db.Users.Where(x => x.username.Equals(UserName));
return user == null ?
Json(true, JsonRequestBehavior.AllowGet) :
Json(string.Format("{0} is not available.", register.UserName), JsonRequestBehavior.AllowGet);
}
When you change the version of your jQuery.js you have to change the validation.js file as well. Different versions are not compatible to each other and you might see strange behaviour in different browsers when you mixup the files.

Resources