[英]ASP.NET MVC Remote Validation logic on Edit
我在MVC中有一个模型和一个actionMethod;
public class employee
{
[Key]
public int id { get; set; }
[Required]
public string employeeID { get; set; }
[Required]
[Remote("doesCnicExist", "employee", AdditionalFields = "employeeID", HttpMethod = "POST", ErrorMessage = "A user with this cnic already exists. Please enter a different cnic.")]
public string cnic { get; set; }
}
[HttpPost]
public JsonResult doesCnicExist(string employeeID, string cnic)
{
var empList = hc.employee.ToList();
bool flag = false;
foreach (employee e in empList)
{
if ((employeeID == e.employeeID) && (cnic == e.cnic))
{
flag = true;
}
}
return Json(flag == false);
}
在Create()
动作上,它很有效。 但是在Edit()
动作中,程序看到cnic
已经存在。 而且我无法使用相同的cnic
更新employee
。 我无法弄清楚如何在编辑时使用额外的employeeID
字段来实现员工对象的统一性?
由于id
是您的唯一标识符,因此您需要将其传递给doesCnicExist()
方法,然后您可以修改逻辑以忽略id
已存在的退出行。 将模型更改为
public class employee
{
[Key]
public int id { get; set; }
....
[Required]
[Remote("doesCnicExist", "employee", AdditionalFields = "id", HttpMethod = "POST", ErrorMessage = "A user with this cnic already exists. Please enter a different cnic.")]
public string cnic { get; set; }
}
和控制器方法
[HttpPost]
public JsonResult doesCnicExist(string cnic, int id)
{
return Json(IsUnique(cnic, id));
}
private bool IsUnique(string cnic, int id)
{
if (id == 0) // its a new object
{
return !hc.employee.Any(x => x.cnic == cnic);
}
else // its an existing object so exclude existing objects with the id
{
return !hc.employee.Any(x => x.cnic == cnic && x.id != id);
}
}
请注意,我已将逻辑分离为单独的方法,因为RemoteAttribute
仅是客户端验证,并且应始终在服务器上执行验证(客户端验证应被视为一个很好的奖励,但恶意用户可以轻松绕过它)。 单独的方法还允许您在Create()
和Edit()
POST方法中对其进行验证,以防止在保存到数据库时抛出可能的异常。
但是因为RemoteAttribute
是客户端(UI)属性,所以它不应该应用于数据模型,您应该遵循最佳实践并使用视图模型 ,其中属性应用于视图模型属性而不是数据模型。 我还建议您对类和属性名称使用常规命名约定(即PascalCase)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.