samantha07
samantha07

Reputation: 507

mvc remote validation

Im not sure why my validation is not working if I try to use an integer AdditionalField.

Here's my code(some parts of the code are omitted):

Model

    public class PersonViewModelBase
    {
    public int PersonID { get; set; }

    [Required]
    [StringLength(15, MinimumLength = 3)]
    [Remote("Checkusername", "Utilities", AdditionalFields = "PersonID")]
    [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")]
    public string UserName { get; set; }

    public string Password { get; set; }
    public string LastName { get; set; }

Controller(Remote)

public JsonResult Checkusername(string username, int PersonID)
    {
        //var user = studentRepository.GetStudents()
        //    .Where(a => a.UserName == username.Trim())
        //    .Where(b => b.PersonID != personID);            
        var user = studentRepository.GetStudents().Where(a => a.UserName == username.Trim());
        if (user.Count() > 0)
        {
            return Json(string.Format("{0} is not available.", username),
                JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
    }

this remote validation is not being called. But if I try to change the additional field to string the application will call the remotevalidation, though it would become "undefined" because the PersonID is an integer

Upvotes: 2

Views: 757

Answers (2)

Raman Agrawal
Raman Agrawal

Reputation: 1

No this is not like this, we can not take the additional field which we have in model. The solution is take any other field like hidden than assign the attribute of value = PersonID in your case, and receive this value in your controller like

View

<input type = "hidden" value = "PersonID " id = hiddenID>

Model

 [Remote("Checkusername", "Utilities", AdditionalFields = "hiddenID ")]

Controller

public JsonResult Checkusername(string username, string hiddenID )
{
  //your code
}

Upvotes: 0

snumpy
snumpy

Reputation: 2878

The AdditionalFields option only sends strings to your action, so you will need to accept it as a string and then manually convert it to an integer.

public JsonResult Checkusername(string username, string PersonID)
{
    int personID = Convert.ToInt32(PersonID);

    var user = studentRepository.GetStudents()
        .Where(a => a.UserName == username.Trim())
        .Where(b => b.PersonID != personID); 

    //var user = studentRepository.GetStudents().Where(a => a.UserName == username.Trim());
    if (user.Count() > 0)
    {
       return Json(string.Format("{0} is not available.", username),
            JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json(true, JsonRequestBehavior.AllowGet);
    }
}

Upvotes: 2

Related Questions