javascript 基于下拉选择 mvc 4 razor c# 的显示/隐藏控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28589969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:14:03  来源:igfitidea点击:

Show/hide control based on dropdown selection mvc 4 razor c#

javascriptc#asp.net-mvcrazor

提问by Steve Ed

Here is my code

这是我的代码

@Html.DropDownListFor(z => z.SelectedReportId, new SelectList(Model.ReportTypes, "Value", "Text", Model.SelectedReportId), "-- Select Report --")
@Html.CheckBoxFor(model => model.IncludePhotos)@Html.LabelFor(model => model.IncludePhotos)

Which generates:

产生:

<select data-val="true" data-val-number="The field SelectedReportId must be a number." data-val-required="The SelectedReportId field is required." id="SelectedReportId" name="SelectedReportId">
    <option value="">-- Select Report --</option>
    <option value="1">Excel Report</option>
    <option value="2">Text Report</option>
</select>
<br />
<input data-val="true" data-val-required="The Include photos in the report field is required." id="IncludePhotos" name="IncludePhotos" type="checkbox" value="true" />

I have one dropdown and a checkbox, I need to disable the checkbox if the user selects the first value in dropdown. Here is the javascript I am using without success

我有一个下拉列表和一个复选框,如果用户选择下拉列表中的第一个值,我需要禁用该复选框。这是我使用的 javascript,但没有成功

$(function () {
    $('#SelectedReportId').change(function () {
        var value = $(this).val();
        if (value == '1') {
            $('#IncludePhotos').show();
        } else {
            $('#IncludePhotos').hide();
        }
    });
});

Appreciate any help, thank you

感谢任何帮助,谢谢

采纳答案by Steve Ed

Included javascript inside a @section scripts{} section and it started working,

在@section scripts{} 部分中包含 javascript 并开始工作,

@section scripts{ <script type="text/javascript">
$(function () {
    $('#SelectedReportId').change(function () {
        var value = $(this).val();
        if (value == '1') {
            $('#IncludePhotos').show();
        } else {
            $('#IncludePhotos').hide();
        }
    });
});</script>}

回答by Muhd Alavu

try this

试试这个

@Html.DropDownListFor(z => z.SelectedReportId, new SelectList(Model.ReportTypes, "Value", "Text", Model.SelectedReportId),new {id="myDropdown"}

@Html.CheckBoxFor(model => model.IncludePhotos,new {id="myCheckbox"})

$(function () {
    $('#myDropdown').change(function () {
        var value = $(this).val();
        var fistVal=$('#myDropdown option:first-child').attr("selected", "selected");
        if (value == fistVal) {
            $('#IncludePhotos').show();
        } else {
            $('#IncludePhotos').hide();
        }
    });
});