[英]Remote Validation on a Dropdown List Combination in MVC 5
有谁知道我如何在MVC 5中对下拉列表组合执行远程验证?
简而言之,我将一个客户分配给一个用户,因此我想确保不会两次将一个客户分配给同一用户。
我已经在控制器中创建了一个验证操作,但是它不起作用。 它告诉我,即使组合不存在于数据库中,也无论组合如何,都已将客户分配给用户。
这是我的模型的样子:
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; }
}
这是控制器中的验证操作:
public JsonResult CustomerAssignedToUser(int CustomerID, int ApplicationUserID)
{
return Json(!db.UserCustomers.Any(x => x.CustomerID == CustomerID && x.ApplicationUserID == ApplicationUserID), JsonRequestBehavior.AllowGet);
}
这是我视图中的两个下拉列表:
@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" })
帮助将不胜感激。 我一生都看不到代码有什么问题。
我设法解决了这个问题。 解决方案非常简单。 我要做的就是在模型内部的其他字段上反向实现相同的数据注释,如下所示:
[Remote("CustomerAssignedToUser", "UserCustomer", AdditionalFields = "ApplicationUserID", ErrorMessage = "The customer has already been assigned to the selected user!")]
public int CustomerID { get; set; }
[Remote("CustomerAssignedToUser", "UserCustomer", AdditionalFields = "CustomerID", ErrorMessage = "The customer has already been assigned to the selected user!")]
public int ApplicationUserID { get; set; }
我发现它不能与下拉列表配合使用,尽管它并不总是立即更新,有时可能需要在下拉列表中进行多次切换才能正确验证。 可能是因为ID是int值,而不是GUID。 当使用字符串和文本框输入(例如,验证名字和姓氏组合)时,该方法非常有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.