c# - 根据数据库值选择 RadioButton

标签 c# asp.net-mvc razor

正在处理 MVC 5 应用程序。

我有一个包含许多列的表格。一列包含项目的单选按钮列表。因为这是一个“编辑” View ,所以我需要正确地预填充选定的单选按钮。 (即选择数据库中的项目)

我的部分 Controller 代码...

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

这是 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
  }  

可用选项为"is"、“否”和“不适用”。例如,在数据库中,如果已选择“否”,则应在加载此 View 时预先选择它。单选按钮显示正确,但 @Checked 无法正常工作。

顺便说一句,我确定存在现有数据,因为我将这行代码放在 foreach 的第一行....

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

有什么建议吗?谢谢!

最佳答案

请试试这个:

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

关于c# - 根据数据库值选择 RadioButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43500457/

相关文章:

javascript - 准备在属性中使用的转义/编码字符

c# - System.Timers.Timer 稳步增加间隔

c# - 多个 OfType Linq?

c# - Html.BeginForm 发布模型为空

asp.net-mvc-3 - 由于 session 而导致单元测试失败

Razor 模板与 SiteEdit UI 2012 onTridion 2011

c# - 使用 TextPointers 选择时不要突出显示换行符

c# - MVC 5 IValidatableObject 不显示错误消息?

c# - MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32'

asp.net-mvc - PDFTron WebViewer - 尝试显示存储在 Azure BLOB 存储中的 XOD 文件时出现 CORS 错误