2012-06-07 60 views
0

訪問字段在下面的代碼我的用戶名不傳遞到遠程驗證函數:MVC遠程驗證從類以上

public string UserName { get; set; } 

public class Numbers 
{ 


      [Display(Name = "Additonal Numbers")] 
      [Remote("NumberExists", "Account", AdditionalFields = "UserName", ErrorMessage = "Serial is already taken.")] 
      public string additionalNumbers { get; set; } 
} 


public List<Numbers> NumberList { get; set; } 

這是一個簡單的例子,但我想從同一個模型通過附加字段在一個列表中,但我似乎無法訪問公共課範圍外的任何內容。

我是否需要將模型的其餘部分以某種方式傳遞到列表中以實現此目的,還是我在這裏做錯了什麼?

+0

你爲什麼要設置這個嵌套類?? !!只需將'additionalNumbers'屬性添加到上面的類中,一切都會很好:) –

+0

您如何實現這一目標? – Sparkle

+0

'UserName'屬性應該在'additionalNumbers'屬性的相同類中 –

回答

0

遠程驗證屬性中的AdditionalFields參數需要與正在驗證的對象處於相同的類中。

..edit ..意見後

public class Numbers 
{ 

      public string UserName { get; set; } 

      [Display(Name = "Additonal Numbers")] 
      [Remote("NumberExists", "Account", AdditionalFields = "UserName", ErrorMessage = "Serial is already taken.")] 
      public string additionalNumbers { get; set; } 
} 

..edit .. 看起來你想要做的是驗證所有的號碼都輸入用戶名獨特的東西。試試這個:

public string UserName { get; set; } 

[Display(Name = "Additonal Numbers")] 
[Remote("NumberExists", "Account", AdditionalFields = "UserName", ErrorMessage = "Serial is already taken.")] 
public List<String> NumberList { get; set; } 

在你NumberExists行動採取字符串列表,而不是隻1串。這將讓你一次驗證你的整個數組。

Public ActionResult NumberExists(List<String> NumberList, String UserName){ 
    //Validate list is unique for username 
} 
+0

您可以添加一些代碼/ – Sparkle

+0

當然,我將UserName字段移動到與additionalNumbers字段相同的類中。 –

+0

是的,但額外的數字需要是一個數字列表? – Sparkle

0

UserName屬性應該是在同一個類中的additionalNumbers屬性:

public class NumbersViewModel 
{ 
    public string UserName { get; set; } 

    [Display(Name = "Additonal Numbers")] 
    [Remote("NumberExists", "Account", AdditionalFields = "UserName", ErrorMessage = "Serial is already taken.")] 
    public string additionalNumbers { get; set; } 

    public List<Numbers> NumberList { get; set; } 
} 
+0

是的,但額外的數字需要是數字列表嗎? – Sparkle

+0

公開列表 NumberList {get;組; }如果我添加兩個@ Html.TextBoxFor(m => m.NumberList})到視圖我從第一個獲取數據 – Sparkle

+0

這與您的問題無關。無論如何,儘量做到這一點'@ Html.EditorFor(m => m.NumberList)'應該工作。 –