Mvc Remote Attribute在查询字符串中发送“undefined”

时间:2015-06-15 17:07:50

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我正在尝试远程验证一些代码和参数,它将undefined作为参数传递。这是我的验证码:

[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public class ValidationController : Controller
{
    public JsonResult IsUserNameAvailable(string userName, int? UserId)
    {
        var users = new BusinessLayer.BdsAdmin.Users();
        if (UserId == null || UserId == 0)
            // Do something
        else // Do something else

        if (users.Count == 0)
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        string msg = string.Format("{0} is already taken and is not available.", userName);
        return Json(msg, JsonRequestBehavior.AllowGet);
    }
}

这是我的模特:

public class EditUserAdministrationViewModel
{
    public int UserId { get; set; }

    [Required(ErrorMessage = "You must enter a user name.")]
    [Display(Name = "User Name")]
    [Remote("IsUserNameAvailable", "Validation", AdditionalFields = "UserId")]
    public string UserName { get; set; }

    // More properties
}

看看Fiddler的请求,这就是我所看到的:

GET /Validation/IsUserNameAvailable?UserName=sara&UserId=undefined

为什么MVC将字符串undefined注入请求而不是实际的UserId?

1 个答案:

答案 0 :(得分:2)

您需要添加

  @Html.HiddenFor(m=>m.UserId) 

在视图中,以便绑定器将它绑定到远程验证控制器,否则没有值绑定