首页 > 解决方案 > 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" }) 

帮助将不胜感激。我一辈子都看不出我的代码有什么问题。

标签: asp.net-mvcasp.net-mvc-5data-annotationsremote-validation

解决方案


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

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


推荐阅读