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);
}
}
Related
i am new to microsofts MVC, and have been trying to make a custom validator.
i managed to call the custom validator, but the parameter is not being sent.
this is the model:
[Remote("VerifyEmail", "CustomValidation")]
public string UserEmail { get; set; }
and here is the controller:
public IActionResult VerifyEmail(string UserEmail)
{
bool EmailUsed = Db.Users.Where(x => x.UserName == UserEmail).Any();
if (EmailUsed)
{
return Json($"Email {UserEmail} is already in use.");
}
return Json(true);
}
the string Username in the custom validator is null. any ideas why?
Im a bit new at mvc, and i dont find out what am i miss. When i launch the login, in the view at foreach (var item in Model) <- the Model gets null, and stops with a System.NullReferenceException. A dont really have a clue why, and i hope somebody can give some advice what's wrong with the following code or where to start looking for the error.
The model:
public class LoginModels
{
public string UserLogin { get; set; }
public string Address { get; set; }
public string Password { get; set; }
public List<string> emailSubject { get; set; }
}
The controller:
public ActionResult Login(string address, string password, LoginModels model)
{
using (Imap imap = new Imap())
{
try
{
imap.ConnectSSL("imap.gmail.com");
imap.Login(address, password);
imap.SelectInbox();
List<long> uids = imap.Search(Flag.All);
model.emailSubject = new List<string>();
foreach (long uid in uids)
{
var eml = imap.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(eml);
model.emailSubject.Add(email.Subject);
}
Session["user"] = new LoginModels() { UserLogin = address, Address = address };
return RedirectToAction("Index", "Home", model.emailSubject);
}
catch (Exception e)
{
ViewBag.exceptionMessage = e;
return View("LoginFailed");
}
}
The view:
#using TheOnlineArchivator.Models;
#model List<TheOnlineArchivator.Models.LoginModels>
#{
ViewBag.Title = "Home";
}
#{
var user = Session["user"] as LoginModels;
if (user != null)
{
<h2>You are logged on as #user.Address</h2>
<table>
#foreach (var item in Model)
{
foreach (var elem in item.emailSubject)
{
<tr>
<td>#elem</td>
</tr>
}
}
</table>
}
}
It looks like you forgot to pass an instance of List<TheOnlineArchivator.Models.LoginModels> to the view when you rendered this view inside your controller action. What you have shown so far is your Login controller action but you didn't show us your Home/Index action. Inside this action you should make sure that you are passing a non-null model to the view:
public class HomeController : Controller
{
public ActionResult Index()
{
List<LoginModels> model = ... go get your model from somewhere and make sure it is not null
return View(model);
}
}
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.
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);
}
}
I have a model item
public class EntryInputModel
{
...
[Required(ErrorMessage = "Description is required.", AllowEmptyStrings = false)]
public virtual string Description { get; set; }
}
and a controller action
public ActionResult Add([Bind(Exclude = "Id")] EntryInputModel newEntry)
{
if (ModelState.IsValid)
{
var entry = Mapper.Map<EntryInputModel, Entry>(newEntry);
repository.Add(entry);
unitOfWork.SaveChanges();
return RedirectToAction("Details", new { id = entry.Id });
}
return RedirectToAction("Create");
}
When I create an EntryInputModel in a unit test, set the Description property to null and pass it to the action method, I still get ModelState.IsValid == true, even though I have debugged and verified that newEntry.Description == null.
Why doesn't this work?
This is because model binding doesn't take place when you invoke an action from a test. Model binding is the process of mapping posted form values to a type and pass it as a parameter to an action method.