2014-10-04 75 views
1

我使用select2插件作为文本框的自动完成。自动完成对数据库中的员工视图进行ajax调用。除非用户打开网络表单编辑记录,否则一切都很好。我需要select2控件加载最初保存在记录中的值,而不管它是否存在于列表中。当我打开编辑表单时,select2控件是空白的。我知道我可以加载这个值,如果它是从ajax调用中返回的json数据,但是如果它不是?我可以看到initSelection中的值,但我不知道如何设置控件文本/值。用原始值填充jquery select2

长话短说,我正在做ajax调用的视图可能会或可能没有原始的员工价值。例如,如果员工最初是从视图中选择的,但是留给了其他分支机构/代理机构,则视图将不再显示。我仍然需要在控件中显示原始值。希望这是有道理的。这是我的代码。我可以在initSelection中看到原始值,但不知道如何在控件中获得它:

var URL = '@Url.Action("GetEmployees", "AssetAssignment")'; 
    var originalValue = ""; 

    $('#AssignedTo').select2({ 
     placeholder: "Type an MJB employee name or county...", 
     minimumInputLength: 3, 
     ajax: { 
      url: URL, 
      dataType: 'json', 
      type: "GET", 
      quietMillis: 50, 
      data: function (term) { 
       return { term: term }; 
      }, 
      results: function (data) { 
       return { results: data.data }; 
      } 
     }, 
     id: function (object) { 
      // store the text vs the id 
      return object.text; 
     },  
     createSearchChoice: function (term, data) { 
      //Allow manually entered text in drop down. 
      if ($(data).filter(function() { 
       return this.text.localeCompare(term)===0; 
      }).length===0) { 
       return { id: "", text: term, county: "" }; 
      } 
     }, 
     initSelection: function (element, callback) { 
      var id = $(element).val(); 
      if (id !== "") { 
       //var id = element.val(); 
       //var text = element.data('option'); 
       //var data = { id: id, text: text }; 
       //callback(data); 
       //alert(JSON.stringify(data)) 
       originalValue = id; 
      } 
     }, 
     formatResult: employeeFormatResult, 
     formatSelection: employeeFormatSelection 
    }); 

    // get other values from the selected item and put them in the appropriate controls 
    $('#AssignedTo').change(function() { 
     var id = $('#AssignedTo').select2('data').id; 
     var county = $('#AssignedTo').select2('data').county; 
     $('#AssignedToEmployeeId').val(id); 
     $('#AssignedToEmployeeCounty').val(county); 
    }); 

}); 

function employeeFormatResult(data) { 
    var markup = "<table class='select2-result'><tr>"; 
    markup += "<td class='select2-result-id'>" + $.trim(data.id) + "</td>"; 
    markup += "<td class='select2-result-text'>" + data.text + "</td>"; 
    markup += "<td class='select2-result-county'>" + data.county + "</td>"; 
    markup += "</tr></table>"; 
    return markup; 
} 

function employeeFormatSelection(data) { 
    return data.text; 
} 

回答

1

它的数字。在我提出问题后,我一直在研究这个问题超过一天半和五分钟。我必须设置该值:

if (originalValue.length > 0) 
    $("#AssignedTo").select2("data", { id: originalValue, text: originalValue }); 

这对我有用,因为我不在乎原始值是否匹配由ajax调用返回的任何内容。