【问题标题】:How to give mandatory field validation for select2 fields in asp.net mvc 4如何对asp.net mvc 4中的select2字段进行强制字段验证
【发布时间】:2014-03-27 06:41:50
【问题描述】:

我在我的 MVC 4.0 项目中使用 select2 插件作为选择列表。

但是当我们使用 select2 时,MVC 的默认验证失败。有时选择列表会出现错误消息,但是当我们从选择列表中选择值时它不会自动清除。

请给我有关任何其他客户端验证的建议

以下是我的项目代码。

.cshtml

     <div class="editor-field">
        <select id="cityid">
            <option></option>
        </select>
        @Html.ValidationMessageFor(model => model.CityID)
        <script type="text/javascript">
            $("#cityid").select2({
                placeholder: "Select City",
                width: "200px"
            });
        </script>
    </div>

型号代码:

    [Required(ErrorMessage="Please select city")]
    public  int CityID { get; set; }

请帮我解决这个问题

【问题讨论】:

    标签: c# asp.net-mvc jquery-select2


    【解决方案1】:

    请查看enter link description here

        (function() {
      var $select = $('select').select2({
        placeholder: 'Choose',
        allowClear: true
      });
    
      /*
       * When you change the value the select via select2, it triggers
       * a 'change' event, but the jquery validation plugin
       * only re-validates on 'blur'
       */
      $select.on('change', function() {
        $(this).trigger('blur');
      });
    
      $('#myForm').validate({
        ignore: 'input[type=hidden], .select2-input, .select2-focusser'
      });
    
      $select.rules('add', 'required');
    }());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多