I am trying to use SELECT2 in ASP.Net in combination with a dropdown list.
This is my .aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="ASPNet_SELECT2_1._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>a SELECT2 implementation in ASP.NET</title>
<script src="scripts/js/jquery-1.12.0.js"></script>
<script src="scripts/js/select2/select2.js"></script>
<link rel="stylesheet" href="css/select2.css" />
<script>
$(document).ready(function () {
$("#" + "<%=dd.ClientID%>").select2({
placeholder: "Select a Subject",
allowClear: true
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="dd" runat="server" ClientIDMode="Static" Width="300px" multiple="multiple"></asp:DropDownList>
</div>
<asp:Button ID="btnGetSelected" runat="server" Text="Get selected items" OnClick="btnGetSelected_Click" /> <asp:Button ID="btnSetSelected" runat="server" Text="Set selected items" OnClick="btnSetSelected_Click" />
<br />
<asp:Literal ID="lit" runat="server"></asp:Literal>
</form>
</body>
</html>
This is my code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASPNet_SELECT2_1
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
for (int i = 0; i < 10; i++)
{
ListItem l = new ListItem("Item " + i.ToString());
dd.Items.Add(l);
}
}
}
protected void btnGetSelected_Click(object sender, EventArgs e)
{
lit.Text = dd.Text;
}
protected void btnSetSelected_Click(object sender, EventArgs e)
{
}
}
}
The binding of the SELECT2 control with my dropdown list works fine. I also have set the "multiple" attribute for the dropdown list to have the multi select functionality. But i am not able to get the selected items. And also am i not able to set these items.
When i select multiple elements and do a postback (for example on button click), then after the postback only one item is selected. And i always get the selected first item.
How can get all selected items and also set multiple selected items on postback and also via code?