3

Working on MVC 5 app.

I have a table with a bunch of columns. One column contains a radio button list of items. Since this is an "edit" view I need to pre-populate the selected radio button properly. (ie select the item that's in the db)

Part of my controller code...

 newVmRecord.SurveyAnswerOption = 
       new SelectList(db.SurveyAnswerOptions, 
           "AnswerOptionText", "AnswerOptionText", ar.SurveyAnswer);

Here's the razor:

  @foreach (SelectListItem item in 
    (IEnumerable<SelectListItem>)Model[i].SurveyAnswerOption)
  {
      @Html.RadioButtonFor(modelItem => Model[i].SelectedSurveyAnswer, 
        Model[i].SurveyAnswerOption, new { @Checked = 
        Model[i].SelectedSurveyAnswer}) @item.Text
  }  

The available options are 'yes', 'no' and 'n/a'. In the database, for example, if 'no' was already selected then it should be pre-selected when this view loads. The radio buttons appear correctly, but, the @Checked doesn't work correctly.

By the way, I am sure there is existing data because I put this line of code as the first line the foreach....

  @Html.DisplayTextFor(modelItem => Model[i].SelectedSurveyAnswer);

Any suggestions? Thanks!

7
  • Have you confirmed that ar.Survey is being populated and there are no casting issues (ie. true/false, yes/no, 1/0)? Apr 19, 2017 at 15:55
  • @KevinRaffay yes. There is data. I tried adding this in the first line of the foreach and it shows data: @Html.DisplayTextFor(modelItem => Model[i].SelectedSurveyAnswer);
    – WebDevGuy2
    Apr 19, 2017 at 16:39
  • 2
    Welll if @checked is translated the checked attribute on the html ... it should just accept the word checked or ' '... so what about @Html.RadioButtonFor(modelItem => Model[i].SelectedSurveyAnswer, Model[i].SurveyAnswerOption, new { @Checked = Model[i].SelectedSurveyAnswer == "yes" ? "checked" : ""} Apr 19, 2017 at 16:46
  • I agree with David -- I recall that "checked" is the attribute. Apr 19, 2017 at 16:58
  • Actually, you don't even want checked="" because simply having the checked attribute makes some browsers check the radio button, so using David's example above will end up with the last radio button in the set being checked, regardless of which one has checked="checked". This messiness with the radio button is why I typically opt for dropdowns instead. Quick fiddle to illustrate.
    – sleeyuen
    Apr 19, 2017 at 17:33

1 Answer 1

0

Please try this:

@foreach (SelectListItem item in (IEnumerable<SelectListItem>)Model[i].SurveyAnswerOption)
  {
      @Html.RadioButtonFor(modelItem => Model[i].SelectedSurveyAnswer,@item.Value, Model[i].SelectedSurveyAnswer == item.Value ? new {Checked = "checked"} : null) @item.Text
  } 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.