Select RadioButton based on database value

Working with MVC Application 5.

I have a table with a bunch of columns. One column contains a list of radio buttons. Since this is an "edit", I need to pre-populate the selected radio button correctly. (i.e. select the item that is in 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 no. For example, in a database, if "no" is already selected, it must be preselected when loading that view. The correct switches are displayed, but @Checked is not working correctly.

By the way, I'm pretty sure there is existing data because I put this line of code in the first line for foreach ....

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

      

Any suggestions? Thank!

+3


source to share


1 answer


Please try the following:



@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
  } 

      

0


source







All Articles