Reputation: 3939
I use a select2 plugin my website. I can't set selected value in select2. Please see my code below.
Html
<input id="drpEditProvider" class="form-control" type="text" value="" tabindex="8" name="ProviderId" data-required="true" />
Script
var attendeeUrl = '@Url.Action("GetProvider", "Admin")';
var pageSize = 100;
$('#drpEditProvider').select2(
{
placeholder: 'Please Select Provider',
//Does the user have to enter any data before sending the ajax request
minimumInputLength: 0,
allowClear: true,
//tags:["red", "green", "blue"],
ajax: {
////How long the user has to pause their typing before sending the next request
//quietMillis: 150,
//The url of the json service
url: attendeeUrl,
dataType: 'jsonp',
//Our search term and what page we are on
data: function (term, page) {
return {
pageSize: pageSize,
pageNum: page,
searchTerm: term
};
},
results: function (data, page) {
//Used to determine whether or not there are more results available,
//and if requests for more data should be sent in the infinite scrolling
var more = (page * pageSize) < data.Total;
return { results: data.Results, more: more };
}
},
initSelection: function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({ id: this, text: this });
});
callback(data);
},
});
Controller and model
public class Select2PagedResult
{
public int Total { get; set; }
public List<Select2Result> Results { get; set; }
}
public class Select2Result
{
public string id { get; set; }
public string text { get; set; }
}
public JsonResult GetProvider(string searchTerm, int pageSize, int pageNum)
{
int Count = 0;
List<Provider> provideres = ProviderHelper.GetAllProvider(searchTerm, out Count);
//Translate the attendees into a format the select2 dropdown expects
Select2PagedResult pagedProvider = new Select2PagedResult();
pagedProvider.Results = new List<Select2Result>();
//Loop through our attendees and translate it into a text value and an id for the select list
foreach (Provider a in provideres)
{
pagedProvider.Results.Add(new Select2Result { id = a.Id.ToString(), text = a.Name });
}
//Set the total count of the results from the query.
pagedProvider.Total = Count;
//Return the data as a jsonp result
return new JsonpResult
{
Data = pagedProvider,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
Upvotes: 1
Views: 5231
Reputation: 3939
Finally I found the answer. You can set selected value in select2
plugin like below.
Select 2 Single selection
$("#drpselector").select2("data", { id: "1", text:"Test 1" });
Select 2 Multiple selection
var arrdata = "1:Test 1,2:Test 2"
var thdprdata = [];
$(arrdata.split(",")).each(function () {
thdprdata.push({ id: this.split(':')[0], text: this.split(':')[1] });});
$("#drpselector").select2("data", thdprdata);
I use this code in my application. It works fine for me.
Upvotes: 4