I have a model and an actionMethod in 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);
}
On Create()
action, it works great. But on Edit()
action, program sees cnic
already exist. And I cannot update employee
with the same cnic
. I cannot figure out how I can use additional employeeID
field to achieve uniquness of employee object while editing?
Since id
is your unique identifier, you need to pass that to the doesCnicExist()
method and then you can modify the logic to ignore exiting rows where the id
already exists. Change the model to
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; }
}
and the controller method to
[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);
}
}
Note that I have separated the logic into a separate method because RemoteAttribute
is client side validation only and validation should always be performed on the server (client side validation should be considered a nice bonus, but a malicious user can easily bypass it). The separate method also allows you to validate it in the Create()
and Edit()
POST methods to prevent a possible exception being thrown when you save to the database.
But because RemoteAttribute
is a client side (UI) attribute, it should not be applied to a data model anyway, and you should be following best practice and using a view model where the attribute is applied to your view model property and not the data model. I also recommend you use normal naming conventions for your classes and property names (ie PascalCase).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.