I am trying to create an online survey.
I have a View where a user can create a Multiple Choice question with as many answer possibilities as the user wishes. Each answer possibility is supposed to have text boxes which represents the following properties:
[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;开发者_JS百科 } // help_text if the user doesnt understand the answer possibility
How should my ViewModel look like, when i dont know how many answer possibilities the user wants?
Thanks
Use javascript and the JSON model binding in MVC3 to help you here.
On the client side create a javascript "object" that matches your server side object
function MultipleChoiceQuestion(choice_number, choice_wording, help_text)
{
this.ChoiceNumber = choice_number;
this.ChoiceWording = choice_wording;
this.HelpText = help_text;
}
Then use javascript to iterate and parse through the DOM to get the variable number of answers.
psuedo-code...
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);
}
Post this with ajax. One downside to this method is that you have to use 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(){}
});
Then on the server side you have your question class as you've already defined it(your property names must match the client side property names), and a container class...
public class QuestionContainer()
{
public List<MultipleChoiceQuestion> Questions {get; set;
}
and your Action takes this as a parameter
public ActionResult Create(QuestionContainer questions)
{
...
}
Phil Haack did an article about this, but before the MVC3 binding was released. It's easier now than what he wrote about.
http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx
you can assign certain class or a ID prefix for each textbox and collect their values using javascript in one comma separated string(or separated by any delimiter you want) and save the result in a Hidden
field which you can access from your controller. you can get the number of textboxes by splitting the value of the hidden field into array of string, so the length of the array will be the number of textboxes in your view
check my answer for similer question here
精彩评论