ASP.Net引入Select2選擇框以及傳值

引入js和css

<!-- 加載 Jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- 加載 Select2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js"></script>

寫一個js在加載頁面時就初始化select2下拉選擇框

<script>
        $(document).ready(function () {
            var selectorx = $('#select2Id').select2({
                placeholder: "Please type or choose",
                placeholderOption: "first",
                allowClear: true
            });
        });
</script>

寫一個select2

<select 
    class="form-control"
    id="select2Id"
    name="Select2"
    DataSourceID="Sql_Id"
    DataTextField="typeName"
    DataValueField="typeValue"
    runat="server">
</select>

寫一個數據源用來查數據

<asp:SqlDataSource ID="Sql_Id" runat="server" ConnectionString="<%$ ConnectionStrings:xxxxxxx %>"
                        SelectCommand="SELECT * FROM xxxxx"></asp:SqlDataSource>

你如果用過asp.net,這裏就不需要我多講了,沒用過就別看了吧,學點啥不好

C#的.cs文件獲取select2選中的值和文本

// 這裏的select2Id就是select2在aspx文件中的id
string select2Value = select2Id.Value;
string select2Text = select2Id.Items[select2Id.SelectedIndex].Text;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章