在mvc应用程序

时间:2016-05-17 14:34:14

标签: javascript jquery asp.net-mvc

下面给出的是我的脚本。我的问题是我有一个隐藏的文本框,只有当我们从dropdownlist中选择“other”时才显示。当我们在回发后输入一个值时显示该值,但该文本框变为然而,invisible.on postback下拉列表值被保留并显示为“其他”,并且只有当我选择下拉列表的另一个值然后再将其更改为“other”时,文本框以及文本才会显示...我可以保留隐藏的或在回发上它的可见状态?

<script type="text/javascript">
  $(document).ready(function () {
    $('#SelectedCategoryId').change(function () {
      if ($('#SelectedCategoryId').val() === '5') {
        $('#other').show(1000);
        $('#other').change(function () {
          var SelectedCategory = $('#other').val().toString();
          $('#hiddenId').val(SelectedCategory);
        });
      }
      else {
        $('#other').hide(1000);
        var SelectedCategory = $('#SelectedCategoryId option:selected').text();
        $('#hiddenId').val(SelectedCategory);
      }
    });
  });
</script>

我的观点

<div id="dropdown" class="form-control dropdown">
 @Html.ValidationMessageFor(m => m.SelectedCategoryId, "*")
 @Html.LabelFor(m => m.Category, "Department :", new { style = "display:inline;" })
 @Html.DropDownListFor(m => m.SelectedCategoryId, new SelectList(Model.Category, "Value", "Text"), "SelectCategory", new { id = "SelectedCategoryId"})
 @Html.ValidationMessageFor(m => m.Other, "*")
 @Html.TextBoxFor(m => m.Other, new { id = "other", @class = "other" ,style = "display: none;" })              
 @Html.HiddenFor(m => m.SelectedCategory, new { id = "hiddenId" })
</div>

1 个答案:

答案 0 :(得分:1)

因为您只检查“更改”事件上的选择值。加载页面时不会发生这种情况。这样做:

function toggleHidden() { //that's your code in a function
    if ($('#SelectedCategoryId').val() === '5') {
        $('#other').show(1000);
        $('#other').change(function () {
            var SelectedCategory = $('#other').val().toString();
            $('#hiddenId').val(SelectedCategory);
        });
    }
    else {
        $('#other').hide(1000);
        var SelectedCategory = $('#SelectedCategoryId option:selected').text();
        $('#hiddenId').val(SelectedCategory);
    }
}

$(document).ready(function () {
    toggleHidden(); //execute the toggle on load
    $('#SelectedCategoryId').change(toggleHidden); //execute the toggle on change
});