簡體   English   中英

在MVC 5中對下拉列表組合進行遠程驗證

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM