简体   繁体   English

如何为asp.net mvc 4中的select2字段提供强制字段验证

[英]How to give mandatory field validation for select2 fields in asp.net mvc 4

I am using select2 plugin for select list in my MVC 4.0 project. 我在我的MVC 4.0项目中使用select2插件作为选择列表。

But the default validation of MVC fails when we use select2. 但是当我们使用select2时,MVC的默认验证失败了。 Sometimes error message occurs for select list but it doesn't get cleared automatically when we select the value from the select list. 有时候选择列表会出现错误消息,但是当我们从选择列表中选择值时,它不会自动清除。

Please give me suggestions about any other client-side validation 请给我关于任何其他客户端验证的建议

Following is my project code. 以下是我的项目代码。

.cshtml .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>

Model code : 型号代码:

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

Please help me to solve this problem 请帮我解决这个问题

Please check this 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');
}());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM