Search code examples
c#asp.netasp.net-mvcasp.net-mvc-4umbraco7

MVC 4 getting values of selected radio buttons


I'm just venturing out into the world of MVC (v4) and I'm having real trouble getting the actual selected values of a list of radiobutton lists. I'm pulling the data from an Umbraco database (but I guess the principle of what I'm trying to do will be the same) where there are list of questions with each question having a list of answers. I'll post everything that I've done so far in the hope that someone more intelligent than I could point me in the right direction:

Here's my content structure

enter image description here

My Model

namespace ICASolution.Models
{
    public class MultipleChoiceViewModel
    {
        public int iQuestionID { get; set; }
        public string zQuestionTitle { get; set; }
        public string zQuestionText { get; set; }
        public List<Answers> lAnswers { get; set; }

    }

    public class Answers
    {
        public int iAnswerID { get; set; }
        public string zAnswerText { get; set; }
        public bool bCorrect { get; set; }
        public string selectedAnswer { get; set; }
    }
}

My surface controller:

namespace ICASolution.Controllers
{
    public class MultipleChoiceSurfaceController : SurfaceController
    {
        //
        // GET: /MultipleChoiceSurface/

        //public ActionResult Index()
        //{
        //    return PartialView("MultipleChoice", new MultipleChoiceViewModel());
        //}
        [HttpPost]
        public ActionResult Grade(MultipleChoiceViewModel model)
        {

            return RedirectToCurrentUmbracoPage();
        }

        public ActionResult Index()
        {
            var TestPage = Umbraco.Content(CurrentPage.Id);
            var questions = new List<MultipleChoiceViewModel>();

            foreach (var child in TestPage.Children)
            {
                var questionid = child.Id;
                var questiontitle = child.GetPropertyValue("questionTitle");
                var questiontext = child.GetPropertyValue("questionText");

                questions.Add(new MultipleChoiceViewModel { iQuestionID = questionid, zQuestionTitle = questiontitle, zQuestionText = questiontext, lAnswers = answerList(questionid) });

            }

            return PartialView("MultipleChoice", questions);
        }

        public List<Answers> answerList(int iMyQuestionID)
        {
            var questionPage = Umbraco.Content(iMyQuestionID);
            var answers = new List<Answers>();


            foreach(var child in questionPage.Children)
            {
                answers.Add(new Answers { iAnswerID = child.Id, zAnswerText = child.GetPropertyValue("answerTitle"), bCorrect =  child.GetPropertyValue("correctAnswer") });
            }

            return answers;
        }

    }
}

and finally my partial:

@model IEnumerable<ICASolution.Models.MultipleChoiceViewModel>


<div class="ethicsTestContainer">
    <div class="col-md-12">
        <div class="col-md-12 noRPadding">
            @using (Html.BeginUmbracoForm<ICASolution.Controllers.MultipleChoiceSurfaceController>("Grade")) { 

                    foreach (var item in Model)
                    {
                        <div class="form-group">
                            <p><strong>@item.zQuestionTitle</strong></p>
                            <p>@item.zQuestionText</p>

                            @{
                                foreach (var answerItem in item.lAnswers)
                                {
                                    <div class="radio radio-danger">
                                        @Html.RadioButton(answerItem.iAnswerID.ToString(), answerItem.iAnswerID, new { @type = "radio", @id = answerItem.iAnswerID, @name = item.iQuestionID })

                                        @*<input type="radio" name="@item.iQuestionID" id="@answerItem.iAnswerID" value="option1">*@
                                        <label for="@answerItem.iAnswerID">
                                            @answerItem.zAnswerText <span>&nbsp;</span>@answerItem.bCorrect
                                        </label>
                                    </div>
                                }
                            }
                        </div>
                    }


                <div class="col-sm-8 col-sm-push-2">
                    <button type="submit" class="btn btn-default btn-block">CLICK HERE TO COMPLETE YOUR ETHICS TEST</button>
                </div>

            }

        </div>
    </div>
</div>

Everything renders fine when displayed to the user:

enter image description here

But I just can't work out how to get the selections that the user has made on the HTTPPOST (basically I need to count the amount of correct answers that they have made).


Solution

  • Your problem is that you are generating the controls for MultipleChoiceViewModel in a foreach loop with generates duplicate name attributes which cannot be bound to a collection (they do not include indexers) and duplicate id attributes which is invalid html. You need to generate the controls in a for loop (or use a custom EditorTemplate for type of MultipleChoiceViewModel)

    You also need to move the selectedAnswer property to MultipleChoiceViewModel (not in selectedAnswer)

    Using a for loop (the model must be IList<MultipleChoiceViewModel>)

    for(int i = 0; i < Model.Count; i++)
    {
      @Html.HiddenFor(m => m[i].iQuestionID) // for post back
      @Html.DisplayFor(m => m[i].zQuestionTitle)
      ... 
      foreach(var item in Model[i].lAnswers)
      {
        @Html.RadioButtonFor(m => m[i].selectedAnswer, item.iAnswerID, new { id = item.iAnswerID })
        <label for="@item.iAnswerID">@item.zAnswerText</label>
      }
    }
    

    To use an EditorTempate, create a partial view in /Views/Shared/EditorTemplates named MultipleChoiceViewModel.cshtml

    @model yourAssembly.MultipleChoiceViewModel
    @Html.HiddenFor(m => m.iQuestionID)
    @Html.DisplayFor(m => m.zQuestionTitle)
    ... 
    foreach(var item in Model.lAnswers)
    {
      @Html.RadioButtonFor(m => m.selectedAnswer, item.iAnswerID, new { id = item.iAnswerID })
      <label for="@item.iAnswerID">@item.zAnswerText</label>
    }
    

    and then in the main view,replace the for loop with

    @Html.EditorFor(m => m)
    

    The EditorFor() method will generate the html based on the template for each item in the collection.

    Side notes: RadioButtonFor() generates type="radio" so adding a html for @type = "radio" is pointless. And NEVER override the name attribute when using html helpers