ShaneKm
ShaneKm

Reputation: 21328

MVC3 Remote Attribute - validation

I have a class Admin:

    public class Admin
    {
        public virtual int AdminId { get; set; }

        [Remote("UsernameAvailable", "Admins")]
        [Display(Name = "lblUsername", ResourceType = typeof(Resources.Admin.Controllers.Admins))]
        public virtual string Username { get; set; }
...

then i have a viewmodel class that's used for a view:

   public class AdminsEditViewModel 
    {

        public Admin Admin { get; set; }

        public IEnumerable<SelectListItem> SelectAdminsInGroup { get; set; }
...

Controller:

public ActionResult UsernameAvailable(string Username)
{
    return Json(this.AdminRepository.GetLoginByUsername(Username), JsonRequestBehavior.AllowGet);

}

However string Username is always null because what is sent to Action is this:

http://localhost/admin/admins/usernameavailable?Admin.Username=ferwf

The problem is that UsernameAvailable sends Admin.Username value and NOT Username value in the http query. how would I do it using a view model?

thanks

Upvotes: 3

Views: 3266

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You could specify a prefix to the default model binder:

public ActionResult UsernameAvailable([Bind(Prefix = "Admin")]string username)
{
    return Json(
        this.AdminRepository.GetLoginByUsername(username), 
        JsonRequestBehavior.AllowGet
    );
}

or use your Admin model:

public ActionResult UsernameAvailable(Admin admin)
{
    return Json(
        this.AdminRepository.GetLoginByUsername(admin.Username), 
        JsonRequestBehavior.AllowGet
    );
}

Now username parameter will be correctly bound assuming the following request:

http://localhost/admin/admins/usernameavailable?Admin.Username=ferwf

Upvotes: 5

Related Questions