2

如果我尝试使用整数 AdditionalField,我不确定为什么我的验证不起作用。

这是我的代码(省略了部分代码):

模型

    public class PersonViewModelBase
    {
    public int PersonID { get; set; }

    [Required]
    [StringLength(15, MinimumLength = 3)]
    [Remote("Checkusername", "Utilities", AdditionalFields = "PersonID")]
    [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")]
    public string UserName { get; set; }

    public string Password { get; set; }
    public string LastName { get; set; }

控制器(远程)

public JsonResult Checkusername(string username, int PersonID)
    {
        //var user = studentRepository.GetStudents()
        //    .Where(a => a.UserName == username.Trim())
        //    .Where(b => b.PersonID != personID);            
        var user = studentRepository.GetStudents().Where(a => a.UserName == username.Trim());
        if (user.Count() > 0)
        {
            return Json(string.Format("{0} is not available.", username),
                JsonRequestBehavior.AllowGet);
        }
        else
        {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
    }

未调用此远程验证。但是,如果我尝试将附加字段更改为字符串,应用程序将调用远程验证,尽管它会变为“未定义”,因为 PersonID 是一个整数

4

2 回答 2

2

AdditionalFields 选项仅向您的操作发送字符串,因此您需要将其作为字符串接受,然后手动将其转换为整数。

public JsonResult Checkusername(string username, string PersonID)
{
    int personID = Convert.ToInt32(PersonID);

    var user = studentRepository.GetStudents()
        .Where(a => a.UserName == username.Trim())
        .Where(b => b.PersonID != personID); 

    //var user = studentRepository.GetStudents().Where(a => a.UserName == username.Trim());
    if (user.Count() > 0)
    {
       return Json(string.Format("{0} is not available.", username),
            JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json(true, JsonRequestBehavior.AllowGet);
    }
}
于 2012-08-21T20:17:21.553 回答
0

不,这不是这样的,我们不能采用模型中的附加字段。解决方案是采用任何其他字段,例如 hidden 而不是在您的情况下分配 value = PersonID 的属性,并在您的控制器中接收此值,例如

看法

<input type = "hidden" value = "PersonID " id = hiddenID>

模型

 [Remote("Checkusername", "Utilities", AdditionalFields = "hiddenID ")]

控制器

public JsonResult Checkusername(string username, string hiddenID )
{
  //your code
}
于 2013-12-03T17:35:26.877 回答