2013-03-02 32 views
3

我意識到在MVC4中使用驗證屬性來執行此任務。但知道我正在處理不同的情況。如何在MVC4中創建自定義驗證?

這裏是模型,其中我有一個集合屬性Choices(這一直有5個元素)和CorectChoice其中是從集合中選擇的索引。

public class MultipleChoiceQuestionTemplate : QuestionTemplate 
{ 
    public MultipleChoiceQuestionTemplate() { ... } 

    [DisplayName("Question")] 
    public string QuestionText { get; set; } 
    public List<string> Choices { get; set; } 

    [DisplayName("Correct Choice")] 
    public int CorrectChoice { get; set; } 
} 

這裏是視圖,觀看演示文稿。

enter image description here

<div id="choices"> 
    @for (int i = 0; i < Model.Choices5.Count; i++) { 
     <div class="choice-container" style="display: block;"> 
     @Html.TextBoxFor(model => model.Choices5[i]) 
     @Html.RadioButtonFor(model => model.CorrectChoice, i) 
     </div> 
    } 
    </div> 

注意,用戶可以在離開輸入空字符串(類型= 「文本」)。我需要驗證選定的索引(單選按鈕)應該有一個字符串。

如何在提交表單之前驗證它?

回答

2

在客戶端,你需要IClientValidateable自定義邏輯或寫自己的手工驗證,不IvalidateableObject這是隻有服務器端。然而,首先要嘗試的是達林的答案,這可能會讓你很容易地認識到錯誤的確切位置。

MVC Radio Button Lists are not grouped when using the HtmlHelper class

如果不工作的另一種選擇至少知道是IClientValidateable ASP.NET MVC implement custom validator use IClientValidatable

如果Darin的第一鏈路解決方案上面沒有出於某種原因,我相信它應該)實際上,你可以逃脫這裏相當簡單以多種方式

  1. 只需截取表單提交和查詢單選按鈕,並確保一個被選中。由於理論上可以有多個單選按鈕類型,因此可以使用選擇器來確保其表單的一部分或包含類類型。如果Darin的解決方案無法解決問題,請告訴我,如果您需要幫助,我會提供解決方案。

  2. 在單選按鈕上使用不顯眼的驗證。只有列表中的第一個會出錯。你將不得不解決一些與CSS類魔法,但解決方案在這裏: ASP.NET MVC 3 unobtrusive validation and radio buttons

相關問題