MVC3 Remote Attribute - Verification

I have an admin class:

    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 is used to represent:

   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, the Username string is always null, because what the Action sent is this:

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

The problem is that UsernameAvailable sends the value Admin.Username and the value NOT Username in the HTTP request. How can I do this using a view model?

thank

+3
source share
1 answer

You can specify the default binder prefix:

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

or use the model Admin:

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

Now the parameter usernamewill be correctly bound on the following request:

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

Source: https://habr.com/ru/post/1788607/


All Articles