javascript - MVC 5 Razor view template binding hide script to a model radiobutton -
currently have custom editortemplate dynamically populates based on incomming model () in razor page. aim able hide individual div 'sub_text' in editor template based on radio value.
model: prime.cs
public class prime{ public list<questionmodel> questions { get; set; } }
model: 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; } }
main view: _reporting.cshtml
@model viewmodels.prime @for (int = 0; < model.questions.count(); i++) //dynamically generate , 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> }
so far closest idea have found add script bottom of template:
<script type="text/javascript"> $(':radio[name=answer').change(function () { // read value of selected radio var value = $(this).val(); var doc if (value == 1) { $('#sub_text').show(); }else{ $('#sub_text').hide(); } }); </script>
which seems able work simpler without using @html.editorfor() in loop.
it looks if script not follow same automatic naming changes happen radiobuttonfor elements. resulting in things this: radio:
<input id="questions_0__answer" name="questions[0].answer" type="radio" value="no" />
while divs , scripts keep referencing directly entered.
how can dynamically hide "sub_text" div based on radiobutton when nested in way?
if there way without feeding in script per editorfor radio group better, solutions welcome.
wrap html generated editortemplate
in container can use relative selectors
@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>
and script can be
$(':radio').change(function () { // associated element containing subtext value var row = $(this).closest('.question').find('.row'); if ($(this).val() == 1) { row.show(); } else { row.hide(); } });
side note: if questionmodel.cshtml
in /views/shared/editortemplates
or /views/yourcontrollername/editortemplates
folder (which should be) code in _reporting.cshtml
should just
@model viewmodels.prime @html.editorfor(x => x.questions)
no loop required. editorfor()
accepts ienumerable<t>
, generates correct html each item in collection.
Comments
Post a Comment