如果我尝试使用整数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);
}
}
未调用此远程验证。但是如果我尝试将附加字段更改为字符串,则应用程序将调用remotevalidation,尽管它将变为“未定义”,因为PersonID是一个整数
答案 0 :(得分: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);
}
}
答案 1 :(得分:0)
不,这不是这个,我们不能采取模型中的附加字段。 解决方案是使用隐藏的任何其他字段,而不是在您的情况下分配value = PersonID的属性,并在控制器中接收此值,如
查看
<input type = "hidden" value = "PersonID " id = hiddenID>
模型
[Remote("Checkusername", "Utilities", AdditionalFields = "hiddenID ")]
控制器
public JsonResult Checkusername(string username, string hiddenID )
{
//your code
}