2011-08-02 25 views
0

我正在嘗試創建在線調查。我如何將未知數量的輸入字段綁定到ViewModel?

我有一個視圖,用戶可以根據用戶的意願創建一個多項選擇問題,並提供儘可能多的答案。每個答案的可能性應該有文本框代表以下屬性:

[Multiple_Choice_Question] 
int choice_number { get; set; } // The order in which the MCQ answer possibility is shown 
int choice_wording { get; set; } // The MCQ answer possibility 
string help_text { get; set; } // help_text if the user doesnt understand the answer possibility 

我的ViewModel應該怎麼樣子,當我不知道用戶有多少答案可能希望?

由於

+0

通用集合? – GalacticCowboy

+0

你是什麼意思? – Nanek

+0

對不起,我誤解了你的問題。我以爲你在談論向用戶展示問題的觀點,可選數量可變。 – GalacticCowboy

回答

0

在MVC3中使用javascript和JSON模型綁定來幫助你。

在客戶端創建一個JavaScript「對象」匹配您的服務器端對象

function MultipleChoiceQuestion(choice_number, choice_wording, help_text) 
{ 
    this.ChoiceNumber = choice_number; 
    this.ChoiceWording = choice_wording; 
    this.HelpText = help_text; 
} 

然後使用JavaScript來迭代,並通過DOM解析來獲取可變數量的答案。

僞代碼...

var ListOfQuestions = []; 
foreach(some dom elements) 
{ 
    var cn = dom.choiceNumber; 
    var cw = dom.choiceWording; 
    var ht = dom.helpText; 

    var question = new MultipleChoiceQuestion(cn, cw, ht); 
    ListOfQuestions.push(question); 

} 

郵政此阿賈克斯。這種方法的一個缺點是你必須使用ajax。

$.ajax({ 
    url:"/yoursite/controller/action", 
    type:"POST", 
    data: JSON.stringify(ListOfQuestions), 
    dataType: 'json', 
    contentType: 'application/json, charset=utf-8', 
    success: function(data){}, 
    error: function(){} 

}); 

然後在你有,你已經將它定義你的問題類的服務器端和容器類(您的屬性名稱必須與客戶端的屬性名稱相匹配)...

public class QuestionContainer() 
{ 
    public List<MultipleChoiceQuestion> Questions {get; set; 
} 

和你的行動將其視爲參數

public ActionResult Create(QuestionContainer questions) 
{ 

    ... 
} 

菲爾哈克做這個的文章,但MVC3結合之前被釋放。現在比他寫的更容易。

http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

0

可以分配某些類或ID前綴爲每個文本框和收集使用javascript它們的值在一個逗號分隔的字符串(或通過任何想要的分隔符分隔)並將結果保存在一個Hidden字段,其你可以從你的控制器訪問。您可以通過拆分隱藏字段的值轉換成字符串數組得到文本框的數量,所以數組的長度將在您的視圖

文本框的數量檢查我的答案similer問題here

相關問題