Data Haunting

Easy Solutions Destination


select2 remote data example in mvc

In this article we will see how Select2 load data from server side while we searched in textbox wrapped with Select2 in MVC. Select2 Provide built in functionality to use Ajax and Json/JsonP . Here we will see how to implement remote data in Select2 .

Let’s see we have following example of binding country in Select2.

Select2 using Ajax Request and Json Response for Remote Data in MVC’s view

As given above Image , here we will implement select2 remote data example in MVC View. While applying given view, if you have any error like Uncaught query function not defined for Select2 then refer my article Uncaught query function not defined for Select2. If you are using Select2 first time in your MVC Application and find any difficulty to implement it , visit Select2 simple example in MVC .

Now let’s see View part of Select2 remote data with Ajax Request and Json dataype in Response .

In above code you can see that here we have made ajax call for remote data by calling remote method and in response we get json Data that is we specified as dataType: ‘json’ . For searching we required minimum two character that is we specified by minimumInputLength: 2 and search term here we passed as term in arguments to Remote method . In response for binding data we have assign data.CountryList to result. Here we used data.CountryList because from remote data we return CountryList as JsonResult in response .

Above we used Select2RemoteDataModel which we define for our example .

Remote method for loading Select2 data

Here we will implement Remote method for loading Select2 data. We used controller “Select2DemoController” and action name “AccessRemoteData” .

In this example as given above code snippets we are trying to load remote data so as an example here we used Dictionary of Country that is dictCountry with key and value pair , which we will see in our response. One more thing here we used is DTO (Data Transfer Object) as Select2DTO for compatibility with Select2 format that is id and text . We used Linq query for filter out search term(which is passed as parameter) from dictCountry Dictionary and at last we return Json Value as CountryList.

Now if you type “un” than you will get result as “United States”, “United Kingdom” and “United Arab Emirates” in your Select2 wrapped element which is perfectly justify our above Image .

Select2 Remote Data Value passing on submit

Select2 Remote Data Passed Value

Here suppose we select “United State” as it’s keyvalue is “3”. So while submitting this value you get value “3” in your CountryName Property .

What is your opinion ?

Here I have given demo for remote data loading for select2 in Mvc . I hope it will be very useful to implement in your MVC Application and you will enjoy it. If you have any query and question, you can comment or you can mail me.

Leave a Reply