asmx ASp.net AJAX使用 ScriptManager
1创建asmx文件
取消
// [System.Web.Script.Services.ScriptService]
的注释(创建能够被asp.net AJAX页面回调的web服务时,请务必删除注释符合)
2创建web方法
例:
[WebMethod] public string HelloWorld() { return "Hello World"; }
下面是一个之前做的二级联动的文本框方法:
asmx中:
//这个示例让Web方法能够访问Session对象 [WebMethod(EnableSession = true)] public void DoSomeThing() { if (Session["myObject"] != null) { } else { } } [WebMethod] //从terr取出region public List<Region> GetRegionInTerritories(int RegionID) { List<Region> Region = new List<Region>(); if (RegionID <0) { Region.Add(new Region(-1,"-请选择-")); return Region; } SqlConnection con = new SqlConnection( WebConfigurationManager.ConnectionStrings["conStr"].ConnectionString); SqlCommand cmd = new SqlCommand( "select * from Region where ID=@RegionID", con); cmd.Parameters.Add(new SqlParameter("@RegionID", SqlDbType.Int)); cmd.Parameters["@RegionID"].Value = RegionID; // List<Region> Region = new List<Region>(); try { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Region.Add(new Region(Convert.ToInt32(reader["ID"]), reader["Name"].ToString())); } reader.Close(); } catch (SqlException ex) { throw new ApplicationException("data error"); } finally { con.Close(); } return Region; }
aspx页面中:
<script type="text/javascript"> function GetRegion(RegionID) { Territories.TerritoriesService.GetRegionInTerritories(RegionID, OnRequestComplete, OnError); } function OnRequestComplete(result) { var ddlRegion = $get("ddlRegion"); //document.getElementById("ddlRegion"); ddlRegion.innerHTML = ""; for (var n = 0; n < result.length; n++) { var option = document.createElement("option"); option.value = result[n].ID; option.innerHTML = result[n].Name; ddlRegion.appendChild(option); } } function OnError(result) { var lbl = $get("lblInfo"); lbl.innerHTML = "<br>" + result.get_message() + "<br>"; } </script>
aspx页面的ScriptManager:
<asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="/TerritoriesService.asmx" /> </Services> </asp:ScriptManager>
posted on 2013-09-06 09:39 YoungPop_Chen 阅读(254) 评论(0) 编辑 收藏 举报