我有一个班级管理员:
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; }
...
然后我有一个用于视图的viewmodel类:
public class AdminsEditViewModel
{
public Admin Admin { get; set; }
public IEnumerable<SelectListItem> SelectAdminsInGroup { get; set; }
...
控制器:
public ActionResult UsernameAvailable(string Username)
{
return Json(this.AdminRepository.GetLoginByUsername(Username), JsonRequestBehavior.AllowGet);
}
但是,字符串Username始终为null,因为发送给Action的是:
http://localhost/admin/admins/usernameavailable?Admin.Username=ferwf
问题是UsernameAvailable在http查询中发送Admin.Username值和NOT Username值。我如何使用视图模型?
感谢
答案 0 :(得分:5)
您可以为默认模型绑定器指定前缀:
public ActionResult UsernameAvailable([Bind(Prefix = "Admin")]string username)
{
return Json(
this.AdminRepository.GetLoginByUsername(username),
JsonRequestBehavior.AllowGet
);
}
或使用您的Admin
型号:
public ActionResult UsernameAvailable(Admin admin)
{
return Json(
this.AdminRepository.GetLoginByUsername(admin.Username),
JsonRequestBehavior.AllowGet
);
}
现在username
参数将正确绑定,假设以下请求:
http://localhost/admin/admins/usernameavailable?Admin.Username=ferwf