I am new to NET MVC and I try to develop an app where user will answer few questions,
I have the following models related to my question:
and a ViewModel
public class QuestionChoiceViewModel
{
public Question Question { get; set; }
public IEnumerable<Choice> Choices { get; set; }
}
In my view I want to display all questions with their responding choices as radio buttons, so i have the following lines in my view Choice/Index.
@model IEnumerable<WebApplication.Models.QuestionChoiceViewModel>
@using (Html.BeginForm("Index", "Choices", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@foreach (var q in Model){
@:<b>Question:</b>
@Html.DisplayFor(modelItem => q.Question.questionText)
<form class="form-group">
@foreach(var c in q.Choices){
<input type="radio" name="@c.choiceText" value="@c.choiceID" />
@c.choiceText
<br />
}
</form>
<br />
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Back" class="btn btn-default" id="btnBack" />
<input type="submit" name="btnSubmit" value="Submit" class="btn btn-default" />
</div>
</div>
</div>
}
I display and can choose from multiple questions without a problem.
And for the final sample of code, see my controller takes only a FormCollection type as paramater
public ActionResult Index(FormCollection form)
The problem: When I debug and see what is in the form -besides Token etc.- is the value of only the first radiobutton group. Lets say I have 10 questions but what I get passed in controller is whatever selected in 1st question. What did I do wrong?
Also, any tips about my style are most welcome, thanks!
At first glance, two things seem out of place:
<form class="form-group">
do not need to be form, and nesting forms can cause problems.Also, name should be some short identifier instead of a text targeted at the user, as I supsect c.choiceText is:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). https://www.w3.org/TR/html401/types.html#type-name