开发者

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 proble开发者_运维百科m 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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜