Here is the article about how to call asp.net function through javascript
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Collections.ObjectModel" %>
<%@ Import Namespace="System.Web.Services" %>
<script runat="server">
[WebMethod]
public static Collection<Location> FillDropDownList(int myValue1)
{
//use myValue1 to fill data
var locations = new Collection<Location>
{
new Location {CountryID = 0, CountryName = "Please Select"},
new Location {CountryID = 1, CountryName = "Country1"},
new Location {CountryID = 2, CountryName = "Country2"},
new Location {CountryID = 3, CountryName = "Country3"},
new Location {CountryID = 4, CountryName = "Country4"},
new Location {CountryID = 5, CountryName = "Country5"}
};
return locations;
}
public class Location
{
public int CountryID { get; set; }
public string CountryName { get; set; }
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#<%= FillDropDownListButton.ClientID %>').click(function() {
doAjaxCall('Default.aspx/FillDropDownList');
return false;
});
function doAjaxCall(url, data) {
var param1 = 1;
$.ajax({
type: 'POST',
url: url,
data: '{myValue1: ' + param1 + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: successHandler
});
}
function successHandler(response) {
var myDropDownList = $('#<%= MyDropDownList.ClientID %>');
myDropDownList.find('options').remove();
var data = response.d;
var doc = $('<div></div>');
for (var i = 0; i < data.length; i++) {
doc.append($('<option></option>').
attr('value', data[i].CountryID).text(data[i].CountryName)
);
}
myDropDownList.append(doc.html());
doc.remove();
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="MyDropDownList" runat="server">
</asp:DropDownList>
<asp:Button ID="FillDropDownListButton" runat="server" Text="Fill DropDownList" />
</div>
</form>
</body>
</html>
No comments:
Post a Comment