2016-11-10 70 views
-1

目前具有动态填充基于剃刀页进来的模型()的自定义EditorTemplate。 目标是能够隐藏个人div'Sub_Text'在编辑器模板中基于无线电值。MVC 5 Razor视图模板结合隐藏脚本模型单选按钮

型号:Prime.cs

public class Prime{ 
    public List<QuestionModel> Questions { get; set; } 
} 

型号:QuestionModel.cs

public class QuestionModel{ 
    public int Id { get; set; } 
    public string Question { get; set; } 
    public string Answer { get; set; } 
    public string SubText { get; set; } 
} 

主视图:_Reporting.cshtml

@model ViewModels.Prime 

@for (int i = 0; i < Model.Questions.Count(); i++) //Dynamically generate and model bind database PolicyHolderKeyQuestions 
{ 
    @Html.EditorFor(x => x.Questions[i], "QuestionModel") 
} 

EditorTemplate:QuestionModel.cshtml

@model ViewModels.QuestionModel 
@{ 
    <div class="col-lg-2"> 
     @Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.Yes) 
     @Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.No) 
     @Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.NA) 
    </div> 
    <div class="col-lg-9"> 
     <div class="row"> 
      <p> 
        <strong>@Model.Question</strong> 
      </p> 
     </div> 
     <div class="row" name="**Sub_Text**"> @* **Hide Me!** *@ 
      @Model.SubText 
     </div> 
    </div> 
} 

到目前为止,我已经找到了最近的想法是一个脚本这样的事情添加到模板的底部:

<script type="text/javascript"> 
    $(':radio[name=Answer').change(function() { 
     // read the value of the selected radio 
     var value = $(this).val(); 
     var doc 
     if (value == 1) { 
      $('#Sub_Text').show(); 
     }else{ 
      $('#Sub_Text').hide(); 
     } 
    }); 
</script> 

这似乎是能够使用一些更简单的工作,而无需使用@ Html.EditorFor ()在一个循环中。

它看起来好像该脚本不遵循与RadioButtonFor元素发生的相同的自动命名更改。导致这样的事情: 收音机:

<input id="Questions_0__Answer" name="Questions[0].Answer" type="radio" value="No" /> 

虽然申报单和脚本只保留引用什么直接输入。

你怎么能动态地隐藏“Sub_Text”的基础上,当它被嵌套在这样的单选按钮DIV

如果有一种方法可以做到这一点,而不需要为每个编辑器输入脚本,那么对于更好的无线电组,但是所有解决方案都是受欢迎的。

回答

0

裹在一个容器由EditorTemplate生成,这样就可以使用相对选择

@model ViewModels.QuestionModel 
<div class="question"> // container 
    <div class="col-lg-2"> 
     @Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.Yes) 
     .... 
    </div> 
    <div class="col-lg-9"> 
     .... 
     <div class="row">@Model.SubText</div> 
    </div> 
</div> 

,然后脚本可以

$(':radio').change(function() { 
    // get the associated element containing the SubText value 
    var row = $(this).closest('.question').find('.row'); 
    if ($(this).val() == 1) { 
     row.show(); 
    } else { 
     row.hide(); 
    } 
}); 

旁注的HTML:如果您QuestionModel.cshtml是在/Views/Shared/EditorTemplates/Views/yourControllerName/EditorTemplates文件夹(它应该是),那么_Reporting.cshtml中的代码应该只是

@model ViewModels.Prime 
@Html.EditorFor(x => x.Questions) 

无环路是必需的。 EditorFor()接受IEnumerable<T>并为集合中的每个项目生成正确的html。

+0

谢谢斯蒂芬让我走下正确的道路。 我发现,在所有产生的无线电组它必须以这种方式开始的应用脚本: '$(“:无线电”)变化(函数(){' – Padre7