从数据库中MVC 4填写选择二下拉框 [英] Fill Select2 dropdown box from database in MVC 4

查看:183
本文介绍了从数据库中MVC 4填写选择二下拉框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助写的jQuery / AJAX来一补选择二的下拉框。

对于那些谁也不知道选择二是什么,这是一个JavaScript扩展,提供Twitter的引导看上去和搜索/预输入功能的HTML选择列表下拉框。欲了解更多信息,看看这里的例子:选择二Github上



更新 - !解决了


所以,我终于把所有在一起,解决我的问题是,我缺少的功能格式化结果列表选择。下面的code产生一个​​有效的选择二的Dropbox型超前完美。

在控制器的Json方式:

 公共JsonResult FetchItems(查询字符串)
{
    DatabaseContext的DbContext =新DatabaseContext(); //初始化的DbContext
    清单<项目> itemsList = dbContext.Items.ToList(); //获取从数据库表中的项目清单
    清单<项目> resultsList =新的List<项目取代; //创建空的结果列表
    的foreach(在itemsList VAR项)
    {
        //如果任何项目包含查询字符串
        如果(item.ItemName.IndexOf(查询,StringComparison.OrdinalIgnoreCase)GT; = 0)
        {
            resultsList.Add(项目); //然后加入项结果列表
        }
    }
    resultsList.Sort(委托(项目C1,C2项){返回c1.ItemName.CompareTo(c2.ItemName);}); //结果列表中ITEMNAME按字母顺序排序
    VAR serialisedJson =从结果resultsList //连载结果列表中成JSON
        新选择
        {
            名称= result.ItemName,//每个JSON对象都会有
            ID = result.ItemID //这两个变量[姓名,身份证]
        };
    返回JSON(serialisedJson,JsonRequestBehavior.AllowGet); //返回序列化的结果列表
}

以上JSON的控制器方法返回序列化的JSON对象的列表,其包含ITEMNAME提供(这个'查询'字符串'查询'来自于搜索框的选择二下拉框)。

下code是JavaScript中的视图(或布局,如果你preFER),以供电选择二下拉框。

使用Javascript:

  $(#hiddenHtmlInput)。SELECT2({
    initSelection:功能(元素,回调){
        VAR elementText =@ ViewBag.currentItemName
        回调({名:elementText});
    },
    占位符:选择项,
    allowClear:真实,
    风格:显示:inline-block的
    minimumInputLength:2,//您可以指定分钟。长查询返回的结果
    阿贾克斯:{
        缓存:假的,
        数据类型:JSON
        键入:GET,
        网址:@ Url.Action(JsonControllerMethod,ControllerName),
        数据:功能(SEARCHTERM){
            返回{查询:SEARCHTERM};
        },
        结果:功能(数据){
            返回{结果:数据};
        }
    },
    formatResult:itemFormatResult,
    formatSelection:函数(项目){
        返回item.name;
    }
    escapeMarkup:功能(M){返回米; }
});

然后在视图的身体,你需要一个隐藏的输入元素,这选择二将呈现保管箱到

HTML:

 <输入ID =hiddenHtmlInput类型=隐藏类=bigdrop的风格=宽度:30%值=/>

或附加MVC剃刀html.hidden元素到视图模式,使您能够发布采摘项目ID回服务器。

HTML(MVC剃刀):

  @ Html.HiddenFor(M = GT; m.ItemModel.ItemId,新{ID =hiddenHtmlInput,@class =bigdrop,风格=WIDTH:30% ,占位符=选择一个项目})


解决方案

解决了!最后。

的完整的jquery低于,现在需要的是两个函数来格式化来自控制器返回的结果。这是因为,保管箱需要一些HTML标记来围绕的结果,以便能够显示它们被包装

此外contractID需要在控制器的一个属性因为没有它的结果在下拉列表中被证明,但他们却无法选择。

  $(#contractName)。SELECT2({
    占位符:输入要查找的合同,
    allowClear:真实,
    minimumInputLength:2,
    阿贾克斯:{
        缓存:假的,
        数据类型:JSON
        键入:GET,
        网址:@ Url.Action(FetchContracts,信息),
        数据:功能(SEARCHTERM){
            返回{查询:SEARCHTERM};
        },
        结果:功能(数据){
            返回{结果:数据};
        }
    },
    formatResult:contractFormatResult,
    formatSelection:contractFormatSelection,
    escapeMarkup:功能(M){返回米; }
});
功能contractFormatResult(合同){
    VAR的标记=<表类='合同结果'>< TR>中;
    如果(contract.name!==未定义){
        标记+ =< D​​IV CLASS ='合同名称'>中+ contract.name +< / DIV>中;
    }
    标记+ =< / TD>< / TR>< /表>
    返回标记;
}功能contractFormatSelection(合同){
    返回contract.name;
}

I need help writing the jquery/ajax to fill a Select2 dropdown box.

For those who don't know what Select2 is, it is a javascript extension to provide Twitter Bootstrap looks and search / type-ahead functionality to an html select list dropdown box. For more information look at the examples here: Select2 Github page


UPDATED - Solved!


So I finally put this all together, and the solution to my problems was that I was missing functions to format the results and the list selection. The code below produces a functioning Select2 dropbox with type-ahead perfectly.

Json Method on Controller:

public JsonResult FetchItems(string query)
{
    DatabaseContext dbContext = new DatabaseContext(); //init dbContext
    List<Item> itemsList = dbContext.Items.ToList(); //fetch list of items from db table
    List<Item> resultsList = new List<Item>; //create empty results list
    foreach(var item in itemsList)
    {   
        //if any item contains the query string
        if (item.ItemName.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0) 
        {
            resultsList.Add(item); //then add item to the results list
        }
    }
    resultsList.Sort(delegate(Item c1, Item c2) { return c1.ItemName.CompareTo(c2.ItemName); }); //sort the results list alphabetically by ItemName
    var serialisedJson = from result in resultsList //serialise the results list into json
        select new
        {
            name = result.ItemName, //each json object will have 
            id = result.ItemID      //these two variables [name, id]
        };
    return Json(serialisedJson , JsonRequestBehavior.AllowGet); //return the serialised results list
}

The Json controller method above returns a list of serialised Json objects, whose ItemName contains the string 'query' provided (this 'query' comes from the search box in the Select2 drop box).

The code below is the Javascript in the view(or layout if you prefer) to power the Select2 drop box.

Javascript:

$("#hiddenHtmlInput").select2({
    initSelection: function (element, callback) {
        var elementText = "@ViewBag.currentItemName";
        callback({ "name": elementText });
    },
    placeholder: "Select an Item",
    allowClear: true,
    style: "display: inline-block",
    minimumInputLength: 2, //you can specify a min. query length to return results
    ajax:{
        cache: false,
        dataType: "json",
        type: "GET",
        url: "@Url.Action("JsonControllerMethod", "ControllerName")",
        data: function (searchTerm) {
            return { query: searchTerm };
        },
        results: function (data) { 
            return {results: data}; 
        }
    },
    formatResult: itemFormatResult,
    formatSelection: function(item){
        return item.name;
    }
    escapeMarkup: function (m) { return m; }
});

Then in the body of the view you need a hidden Input element, which Select2 will render the dropbox to.

Html:

<input id="hiddenHtmlInput" type="hidden" class="bigdrop" style="width: 30%" value=""/>

Or attach a MVC Razor html.hidden element to your view model to enable you to post the picked item Id back to the server.

Html (MVC Razor):

@Html.HiddenFor(m => m.ItemModel.ItemId, new { id = "hiddenHtmlInput", @class = "bigdrop", style = "width: 30%", placeholder = "Select an Item" })

解决方案

Solved! Finally.

The full jquery is below, what was needed were two functions to format the returned results from the controller. This is because the dropbox needs some html markup to be wrapped around the results in order to be able to display them.

Also contractID was needed as an attribute in the controller as without it results were shown in the dropdown, but they could not be selected.

$("#contractName").select2({
    placeholder: "Type to find a Contract",
    allowClear: true,
    minimumInputLength: 2,
    ajax: {
        cache: false,
        dataType: "json",
        type: "GET",
        url: "@Url.Action("FetchContracts", "Leads")",
        data: function(searchTerm){
            return { query: searchTerm };
        },
        results: function(data){
            return { results: data };
        }
    },
    formatResult: contractFormatResult,
    formatSelection: contractFormatSelection,
    escapeMarkup: function (m) { return m; }
});


function contractFormatResult(contract) {
    var markup = "<table class='contract-result'><tr>";
    if (contract.name !== undefined) {
        markup += "<div class='contract-name'>" + contract.name + "</div>";
    }
    markup += "</td></tr></table>"
    return markup;
}

function contractFormatSelection(contract) {
    return contract.name;
}

这篇关于从数据库中MVC 4填写选择二下拉框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆