Bind DropDownlist/select with JQuery in Asp.Net as follows
<script src="js/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="js/jquery.selectboxes.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(function(){ getModels(); });
function getModels()
{
$.ajax({
type: "POST",
url: "Myservice.asmx/LoadCountries",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
$.each(response.d, function(i, _response) {
$('#ddlCountry').append('<option value="' + _response.ID+ '">' + _response.Name + '</option>'); });
}
});
}
</script>
<div>
<select id="ddlCountry" name="ddlCountry"></select>
</div>
Myservice.asmx code follows here
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Myservice : System.Web.Services.WebService
{
[WebMethod]
public List<Country> LoadCountries()
{
SqlConnection con = new SqlConnection(@"your connection");
SqlCommand cmd = new SqlCommand("select ID,Name from CountryTable",con);
con.Open();
DataSet ds=new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
List<Country> Countries = new List<Country>();
Country c = new Country();
if (ds.Tables[0].Rows.Count > 0)
{
c.ID = "0";
c.Name = "--Select--";
Countries.Add(c);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
c = new Country();
c.ID = ds.Tables[0].Rows[i]["ID"].ToString();
c.Name = ds.Tables[0].Rows[i]["Name"].ToString();
Countries.Add(c);
}
}
return Countries;
}
}
public class Country
{
private string _ID;
private string _Name;
public string ID
{
get { return _ID; }
set { _ID = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
o/p:
Tag: asmx, Asp.net, calling server method from javascript, jquery, multiline dropdownlist asp.net, select
No comments:
Post a Comment