0

I am trying to fill a dropdown which use Select2 Jquery add-on using asp.net mvc4. I have already search the stackoverflow and found the related topic as below ;

Fill Select2 dropdown box from database in MVC 4

But in my project i cant get this work.

In my View

<div class="control-group">
                            <label class="control-label">Proje Adı</label>
                            <div class="controls">
                                 <select id="PROJECTID">

                                     </select>
                                 </div>
</div>

In my controller i wrote my action which returns the JSON and i have tested this action with manuel entries and it is OK. I can see the JSON result.

  public JsonResult FetchItems(string query)
        {
            List<CRM_PROJECTS> projectList = db.CRM_PROJECTS.Where(p => p.IS_VALID == 1 && p.NAME != null).ToList(); //fetch list of items from db table
            List<CRM_PROJECTS> resultProjectList = new List<CRM_PROJECTS>(); //create empty results list
            foreach (var item in projectList)
            {
                //if any item contains the query string
                if (item.NAME.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    resultProjectList.Add(item); //then add item to the results list
                }
            }
            //resultProjectList.Sort(delegate(Item c1, Item c2) { return c1.ItemName.CompareTo(c2.ItemName); }); //sort the results list alphabetically by ItemName
            var serialisedJsonProjects = from result in resultProjectList //serialise the results list into json
                select new
                {
                    name = result.NAME, //each json object will have 
                    id = result.ID      //these two variables [name, id]
                };
            return Json(serialisedJsonProjects, JsonRequestBehavior.AllowGet); //return the serialised results list
        }

In the select2.js file i have implemented the Jquery part of code.

 $(document).ready(function () {
        $("#PROJECTID").select2({

            placeholder: "Type to find a Contract",
            allowClear: true,
            minimumInputLength: 2,
            ajax:{ 
                cache: false,
                dataType: "json",
                type: "GET",
                url: "/AddNewOpp/FetchItems",               
                data: function (searchTerm) {
                    return { query: searchTerm };
                },
                results: function (data) { 
                    return {results: data}; 
                }
            },
            escapeMarkup: function (m) { return m; }
        });

 });

I could not populate my drop-down and it seems i am unable to call my url:"/AddNewOpp/FetchItems" in the ajax part of the jquery .

2 Answers 2

1

I am using below code in js file:

jquery:

function getEoOrgPositions() {
        $.ajax({
            url: "/GetDataHandler/GetEoOrgPosition",
            type: "POST",
            data: { action: '1' },
            dataType: "json",
            success: function (data) {
                $.each(data, function (key, value) {
                    $('#selectListOrg')
                        .append($("<option></option>")
                        .attr("value", key)
                        .text(value));
                    options.push({ value: key, text: value });
                });
             }
        });
}

My controller name is GetDataHandler :

       [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult GetEoOrgPosition(string action)
        {
            return Json(_db.GetEoOrgPosition(action), JsonRequestBehavior.AllowGet);
        }

Context DB:

    public Dictionary<string, string> GetEoOrgPosition(string action)
    {
        var data = new DataTable();
      var postlist=new Dictionary<string, string>( );
        using (var connection = new SqlConnection(_connectionString))
        {
            using (var command = new SqlCommand())
            {
                command.Connection = connection;
                command.CommandText = string.Format(
                                      "select PosSysCode , PosParentSysCode , EOSysNum , PosName + ' : ' + PrsName + ' ' + PrsLastName as FullPostName " +
                                      "FROM EOOrgPosition " +
                                      "inner join EOPersons on EOOrgPosition.CA_Persons = EOPersons.CA_Persons " +
                                      "left outer join vwEOUsers usr on (usr.UsrPrsCode = EOPersons.PrsCode) and (usr.UsrState <> 'active') " +
                                      "WHERE usr.EOSysNum IN (select WhichCode from EOPermAssign WHERE OwnerCode = {0} AND Status = 4) order by FullPostName",
                                      action);

                using (var da = new SqlDataAdapter(command))
                {
                    try
                    {
                        da.Fill(data);
                        postlist =
                   data.Rows.Cast<DataRow>()
                       .ToDictionary(item => item["PosSysCode"].ToString(),
                                     item => item["FullPostName"].ToString());
                    }
                    catch
                    {
                    }
                }
            }
        }

        return postlist;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Could you please your action and view also ? Thanks
I edit my answer.Look this answer and this
Did you use select2 box ?
0

SOLVED

VIEW: You need to put an input element wih type="hidden" attribute.

@Html.HiddenFor(m => m.CUSTOMERID, new { id = "CUSTOMERID", @class = " input-block-level  bigdrop", placeholder = "Search for customer" })

CONTROLLER: Aim is getting data which you want to fill the dropdown with, and return in json.

public JsonResult FetchItemsCustomer(string query)
        {
            List<CRM_CUSTOMERS> projectList = db.CRM_CUSTOMERS.Where(p => p.IS_VALID == 1 && p.NAME != null).ToList(); //fetch list of items from db table
            List<CRM_CUSTOMERS> resultProjectList = new List<CRM_CUSTOMERS>(); //create empty results list
            foreach (var item in projectList)
            {
                //if any item contains the query string
                if (item.NAME.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    resultProjectList.Add(item); //then add item to the results list
                }
            }
            //resultProjectList.Sort(delegate(Item c1, Item c2) { return c1.ItemName.CompareTo(c2.ItemName); }); //sort the results list alphabetically by ItemName
            var serialisedJsonProjects = from result in resultProjectList //serialise the results list into json
                                         select new
                                         {
                                             name = result.NAME, //each json object will have 
                                             id = result.ID      //these two variables [name, id]
                                         };
            return Json(serialisedJsonProjects, JsonRequestBehavior.AllowGet); //return the serialised results list
        }

JQUERY AJAX PART:

$("#CUSTOMERID").select2({
        minimumInputLength: 4,
        ajax: {
            url: "/AddNewOpp/FetchItemsCustomer/",
            dataType: 'json',
            quietMillis: 100,
            data: function (searchTerm) {
                return { query: searchTerm };
            },
            results: function (data) {
                return { results: data };
            }
        },
        formatNoMatches: function () {
            $("#addAsCustomer").fadeIn(1000);
            return "Aradığınız müşteri sistemde kayıtlı değil,\"Yeni Ekle\" butonuna tiklayiniz";
        },
        formatInputTooShort: function (input, min) {
            $("#addAsCustomer").fadeOut(500);
            var n = min - input.length; return "" + n + " karakter daha giriniz" + (n == 1 ? "" : "");
        },

        formatResult: contractFormatResult,
        formatSelection: contractFormatSelection,
        escapeMarkup: function (m) { return m; }
    });

2 Comments

great that you solved the problem, i am having some trouble too. first of all do you need to define the select2 dropdown anywhere or is this code enough, and second: after using your solved code i got the error contractFormatResult is not defined. it is in the script on almost the last line, do you define this somewhere?
Did you try with removing this line ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.