0

我正在尝试使用 asp.net mvc4 填充使用 Select2 Jquery 附加组件的下拉列表。我已经搜索了stackoverflow并找到了相关主题,如下所示;

从 MVC 4 的数据库中填充 Select2 下拉框

但在我的项目中,我无法完成这项工作。

在我看来

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

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

In my controlleri 编写了返回 JSON 的操作,并且我已经使用手动条目测试了此操作,并且没问题。我可以看到 JSON 结果。

  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
        }

在 select2.js 文件中,我实现了代码的 Jquery 部分。

 $(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; }
        });

 });

我无法填充我的下拉列表,似乎我无法在 jquery 的 ajax 部分调用我的 url:"/AddNewOpp/FetchItems" 。

4

2 回答 2

1

我在 js 文件中使用以下代码:

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 });
                });
             }
        });
}

我的控制器名称是 GetDataHandler :

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

上下文数据库:

    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;
    }
于 2013-09-18T10:29:18.843 回答
0

解决了

视图: 您需要放置一个带有 type="hidden" 属性的输入元素。

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

CONTROLLER:目标是获取要填充下拉列表的数据,并以 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 部分:

$("#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; }
    });
于 2013-09-20T05:44:51.533 回答