0

JQuery UI Autocomplete (Combobox)을 ASP.NET MVC3의 드롭 다운 목록과 함께 사용하려고합니다. 여기 JQuery 자동 완성 콤보 박스 : MVC3 유효성 검사가 작동하지 않습니다.

내보기에 코드의 관련 섹션 : (. 4-10 드롭 다운 목록에서 아무데도있다)

<div class="editor-label"> 
     @Html.LabelFor(model => model.MerchantID, "Merchant") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownList("MerchantID", null, String.Empty, new { @class = "combobox" }) 
     @Html.ValidationMessageFor(model => model.MerchantID) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.FinancialAccountID, "FinancialAccount") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownList("FinancialAccountID", null, String.Empty, new { @class = "combobox" }) 
     @Html.ValidationMessageFor(model => model.FinancialAccountID) 
    </div> 

다음

는 본질적으로 복사 자바 스크립트 파일의 내용입니다 jquery-ui website :

(function ($) { 
    $.widget("ui.combobox", { 
     _create: function() { 
      var input, 
        self = this, 
        select = this.element.hide(), 
        selected = select.children(":selected"), 
        value = selected.val() ? selected.text() : "", 
        wrapper = this.wrapper = $("<span>") 
         .addClass("ui-combobox") 
         .insertAfter(select); 

      input = $("<input>") 
        .appendTo(wrapper) 
        .val(value) 
        .addClass("ui-state-default ui-combobox-input") 
        .autocomplete({ 
         delay: 0, 
         minLength: 0, 
         source: function (request, response) { 
          var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i"); 
          response(select.children("option").map(function() { 
           var text = $(this).text(); 
           if (this.value && (!request.term || matcher.test(text))) 
            return { 
             label: text.replace(
              new RegExp(
               "(?![^&;]+;)(?!<[^<>]*)(" + 
               $.ui.autocomplete.escapeRegex(request.term) + 
               ")(?![^<>]*>)(?![^&;]+;)", "gi" 
              ), "<strong>$1</strong>"), 
             value: text, 
             option: this 
            }; 
          })); 
         }, 
         select: function (event, ui) { 
          ui.item.option.selected = true; 
          self._trigger("selected", event, { 
           item: ui.item.option 
          }); 
         }, 
         change: function (event, ui) { 
          if (!ui.item) { 
           var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"), 
            valid = false; 
           select.children("option").each(function() { 
            if ($(this).text().match(matcher)) { 
             this.selected = valid = true; 
             return false; 
            } 
           }); 
           if (!valid) { 
            // remove invalid value, as it didn't match anything 
            $(this).val(""); 
            select.val(""); 
            input.data("autocomplete").term = ""; 
            return false; 
           } 
          } 
         } 
        }) 
        .addClass("ui-widget ui-widget-content ui-corner-left"); 

      input.data("autocomplete")._renderItem = function (ul, item) { 
       return $("<li></li>") 
         .data("item.autocomplete", item) 
         .append("<a>" + item.label + "</a>") 
         .appendTo(ul); 
      }; 

      $("<a>") 
        .attr("tabIndex", -1) 
        .attr("title", "Show All Items") 
        .appendTo(wrapper) 
        .button({ 
         icons: { 
          primary: "ui-icon-triangle-1-s" 
         }, 
         text: false 
        }) 
        .removeClass("ui-corner-all") 
        .addClass("ui-corner-right ui-combobox-toggle") 
        .click(function() { 
         // close if already visible 
         if (input.autocomplete("widget").is(":visible")) { 
          input.autocomplete("close"); 
          return; 
         } 

         // work around a bug (likely same cause as #5265) 
         $(this).blur(); 

         // pass empty string as value to search for, displaying all results 
         input.autocomplete("search", ""); 
         input.focus(); 
        }); 
     }, 

     destroy: function() { 
      this.wrapper.remove(); 
      this.element.show(); 
      $.Widget.prototype.destroy.call(this); 
     } 
    }); 
})(jQuery); 

$(function() { 
    $(".combobox").combobox(); 
}); 

나는 데 문제가 입력 한 값에서 수행 유효성 검사 할 수없는 것이다. 예를 들어 비워 두어 제출하면 잘못된 정보가 입력되었다는 오류가 표시되지 않습니다. 그러나 combobox 기능을 사용하지 않도록 combobox() 호출을 주석 처리하면 유효성 검사가 제대로 작동합니다.

이 문제에 대해 stackoverflow에서 일부 검색을 수행했지만이 특정 상황과 일치하는 항목을 찾을 수 없습니다.

편집 : 실제로 유효성 검사가 수행된다는 것을 발견했지만, 제출하기 전에 다른 필드를 클릭해야만 이상합니다. 그래서 빈 텍스트를 콤보 상자에 입력 한 다음 텍스트 필드를 클릭하고 제출하면 제대로 작동합니다 (유효성 검사 오류를 보여줍니다). 그러나 콤보 상자에 빈 텍스트를 입력하고 제출하면 유효성 검사 오류가 표시되지 않습니다. 어떤 아이디어?

+1

여러분의 코드와 jquery 예제 사이에 유일한 차이점은 ID와 반대로 클래스에 따라 콤보 상자 기능을 적용한다는 것입니다. 먼저 ID별로 단일 요소에만 적용 해 보았습니까? – Shawn

+0

@Shawn 답장을 보내 주셔서 감사합니다. 나는 당신의 제안을 시도했지만, 불행히도 그 행동은 변하지 않았습니다. 그러나, 나는 나의 포스트에 추가 한 문제에 대한 자세한 내용을 관찰했다. 나는 검증이 실제로 일어난다는 것을 알았지 만, 제출하기 전에 다른 필드를 클릭하는 경우에만 이상합니다. 그래서 빈 텍스트를 콤보 상자에 입력 한 다음 텍스트 필드를 클릭하고 제출하면 제대로 작동합니다 (유효성 검사 오류를 보여줍니다). 그러나 콤보 상자에 빈 텍스트를 입력하고 제출하면 유효성 검사 오류가 표시되지 않습니다. 어떤 아이디어? – Danation

답변

1

좋아, 문제를 알았어.

제출 버튼을 누를 때 전에 잘못된 입력이 감지되었을 때 선택한 항목을 지운 Autocomplete JQuery가 호출되었습니다. 사용자가 입력을 시작하고 유효한 항목을 선택할 경우에만 다시 선택으로

if (!valid) { 
    // remove invalid value, as it didn't match anything 
    $(this).val(""); 
    select.val(""); 
    input.data("autocomplete").term = ""; 
    return false; 
} 

그래서 나는 즉시 명확 선택한 항목을 만들어이 무슨 뜻 부분입니다.

source: function (request, response) { 
    select.val(""); //as soon as typing is started, the select input is cleared. This makes sure validation always occurs 
    var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i"); 
    response(select.children("option").map(function() { 
     var text = $(this).text(); 
     if (this.value && (!request.term || matcher.test(text))) 
      return { 
       label: text.replace(
        new RegExp(
         "(?![^&;]+;)(?!<[^<>]*)(" + 
         $.ui.autocomplete.escapeRegex(request.term) + 
         ")(?![^<>]*>)(?![^&;]+;)", "gi" 
        ), "<strong>$1</strong>"), 
       value: text, 
       option: this 
      }; 
    })); 
}, 
+0

도움이된다면,이 두 가지 기능을 어디에 포함 시키시겠습니까? – learning

+0

@learning 내 원래 질문은 어떤 방법으로 (아마도 번들을 통해) 페이지에 포함되어야하는 전체 자바 스크립트 코드를 보여주었습니다. 내 대답은 코드의 일부 (자동 완성의 소스 매개 변수)를 변경합니다. 경고로, jQuery, jQuery UI 또는 ASP.NET MVC의 최신 버전에서는이 기능을 테스트하지 않았습니다. – Danation

+1

제가 사용한 해결책은 아래 링크에 있습니다. 바로 입력을 지우고 싶습니다. 이걸 내 combobox +1에 추가했습니다. http://stackoverflow.com/questions/13516841/how-to-get-unobtrusive-validation-on-my-jqueryui-element-combobox – joetinger

관련 문제