3

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

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

I would recommend the second approach, basically think of it like just another action method, in that case the default model binder would bind Admin, not the username string.
that worked. however I had to bind to "AdminViewModel" and not "Admin" like so: public ActionResult UsernameAvailable(AdminsEditViewModel row)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.