我在MVC中有一個模型和一個actionMethod;編輯的ASP.NET MVC遠程驗證邏輯
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
已經存在。我不能更新employee
與cnic
相同。我無法弄清楚如何在編輯時使用額外的employeeID
字段來實現員工對象的唯一性?
'int id'和'string employeeID'有什麼區別?你需要顯示你嘗試過的'doesCnicExist()'方法。 –
@StephenMuecke'int id'由表的數據庫自動生成,並且'Employee ID'由組織分配。我很抱歉,我完全無法考慮這種情況的可能邏輯 - 對於'doesCnicExist()'。這就是我問這個問題的原因。 – Jogi
但你說它適用於你的'Create()'動作。所以顯示它,然後它可以被修改爲適用於'Edit()'方法。 (只要'id'和'employeeID'字段到了,有兩個標識符字段有什麼意義? - 您應該使用'AdditionalFields'中的'id'字段,因爲這是關鍵字) –