Reputation: 27
i want to get select values of jquery select2 plugin in asp.net code behind.
Here is my source
Client Side:
<select id="ddlcountry" runat="server" class="select" style="width: 100%;">
</select>
Code Behind:
var query1 = from pcountry in CTX.Countries
orderby pcountry.Country1 ascending
select new
{
pcountry.CountryId,
pcountry.CountryName
};
if (query1 != null)
{
ddlcountry.DataSource = query1.ToList();
ddlcountry.DataValueField = "CountryId";
ddlcountry.DataTextField = "CountryName";
ddlcountry.DataBind();
ddlcountry.Multiple = true;
}
protected void btnSave_Click(object sender, EventArgs e)
{
Now i want to get all the selected country values here ?
}
Please help me,i will be very thankful.
Upvotes: 1
Views: 798
Reputation: 6586
You can just loop through the items collection to find out which countries have been selected.
foreach (ListItem li in ddlcountry.Items) {
if ((li.Selected)) {
//Selected Country
}
}
Upvotes: 0
Reputation: 27
Thanks Lopsided,i appreciate your kind help.I tried this but it doesn't work for me.
According to your answer i thought some solution,should i get the select2 option list value in client side and store it into hiddenfield and then i get the hidden field value into server side code?
Upvotes: 0
Reputation: 4150
If you're not creating the <select>
element as an <ASP:DropDownList>
control, then I don't believe you will have access to properties and methods such as "Datasource", etc. You can, however, access HTML elements that have the runat="server"
attribute added.
I believe the <option>
tag is of the generic HTML control type. I stick to VB.Net, so I'll have to write some psuedo code for you...
For each o as HtmlGenericControl in ddlcountry.Children.ofType(of HtmlGenericControl)
If o.Attributes("selected") then
' Here you can access your option value using the "value" attribute (and InnerHtml works too, I think)
End if
Next o
Here's a link to an answer where I showed how to loop through generic controls using a working example:
Upvotes: 0