1

我學習asp.net的MVC 5.顯示和隱藏基於下拉列表ASP MVC 5

dropdownlistfor正在完善,並顯示根據其值右場。 但問題是當頁面加載第一次顯示所有字段..

問題是:我想默認顯示什麼,當頁面第一次加載。

我CSHTML:

<div class="form-group"> 
        <div class="col-md-10"> 
         @Html.DropDownListFor(m => m.PaymentMethod, ViewBag.PayTypeList as List<SelectListItem>, new { @class = "btn btn-primary btn-lg dropdown-toggle", @id = "PaymentId" }) 
         <div id="PaypalButton"> 
          <br/> 
          <script src="https://www.paypalobjects.com/api/button.js?" 
            data-merchant="braintree" 
            data-id="paypal-button" 
            data-button="checkout" 
            data-color="gold" 
            data-size="medium" 
            data-shape="pill" 
            data-button_disabled="true"> 
          </script> 
          <!--data-button_type="paypal_submit"--> 
         </div> 
         <div id="EcheckForm"> 
          <div class="form-group"> 
           <div class="col-md-10"> 
            @Html.TextBoxFor(m => m.VecInsNum, new { @class = "form-control input-lg", placeholder = "Vehicle Isurance Number", required = "required", tabindex = 18 }) 
            @Html.ValidationMessageFor(m => m.VecInsNum, null, new { @class = "text-danger" }) 
           </div> 
          </div> 
         </div> 
        </div> 

和JS:

@section Scripts { 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#PaymentId').change(function() { 
      var value = $(this).val(); 
      if (value == '1') { 
       $('#PaypalButton').show(); 
       $('#EcheckForm').hide(); 
      } else if (value == '2') { 
       $('#PaypalButton').hide(); 
       $('#EcheckForm').show(); 
      } else { 
       $('#PaypalButton').hide(); 
       $('#EcheckForm').hide(); 
      } 
     }); 
    }); 

當頁面第一次加載: enter image description here

當我選擇貝寶: enter image description here

當我選擇E-檢查: enter image description here

當我回到默認: enter image description here

回答

3

首先,創建一個包含在它裏面隱藏方法的函數:

// hide all div options 
function hideOnLoad() { 
    $('#PaypalButton').hide(); 
    $('#EcheckForm').hide(); 
} 

然後,調用上面的函數隱藏所有選項被選擇時頁面加載在第一時間和當默認值個元件,如下所示:

$(document).ready(function() { 
    hideOnLoad(); // add this line 
    $('#PaymentId').change(function() { 
     var value = $(this).val(); 
     if (value == '1') { 
      $('#PaypalButton').show(); 
      $('#EcheckForm').hide(); 
     } else if (value == '2') { 
      $('#PaypalButton').hide(); 
      $('#EcheckForm').show(); 
     } else { 
      hideOnLoad(); 
     } 
    }); 
}); 

簡化的例子:JSFiddle Demonstration

相關問題