Does anyone know how I can perform remote validation on a drop-down list combination in MVC 5?
In short, I assign a customer to a user so I want to ensure that a customer can't be assigned to the same user twice.
I have created a validation action in my controller, but it does not work. It tells me that the customer has been assigned to the user regardless of the combination even when the combination does not exist in the database.
Here is what my model looks like:
public class UserCustomer : BaseAttributes
{
[Key]
public int UserCustomerID { get; set; }
[Remote("CustomerAssignedToUser", "UserCustomer", AdditionalFields = "ApplicationUserID", ErrorMessage = "The customer has already been assigned to the selected user!")]
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
public int ApplicationUserID { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
Here is the validation action in my controller:
public JsonResult CustomerAssignedToUser(int CustomerID, int ApplicationUserID)
{
return Json(!db.UserCustomers.Any(x => x.CustomerID == CustomerID && x.ApplicationUserID == ApplicationUserID), JsonRequestBehavior.AllowGet);
}
Here are the two drop-down lists in my view:
@Html.DropDownListFor(model => model.CustomerID, new SelectList((System.Collections.IEnumerable)ViewData["CustomerID"], "Value", "Text"), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.CustomerID, "", new { @class = "text-danger" })
@Html.DropDownListFor(model => model.ApplicationUserID, new SelectList((System.Collections.IEnumerable)ViewData["ApplicationUserID"], "Value", "Text"), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ApplicationUserID, "", new { @class = "text-danger" })
Help will be appreciated. I for the life of me can't see what is wrong with my code.