在MVC 5中对下拉列表组合进行远程验证

时间:2019-01-29 18:31:01

标签: asp.net-mvc asp.net-mvc-5 data-annotations remote-validation

有人知道我如何在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" }) 

我们将不胜感激。我一生都看不到我的代码有什么问题。

1 个答案:

答案 0 :(得分:0)

我设法解决了这个问题。解决方案非常简单。我要做的就是在模型内部的其他字段上反向实现相同的数据批注,如下所示:

[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。当使用字符串和文本框输入(例如,验证名字和姓氏组合)时,该方法非常有效。