2014年7月17日 星期四

[AJAX] 使用ASP.NET Ajax與jQuery Ajax實作連動下拉式選單

說明:
使用ASP.NET Ajax與jQuery Ajax實作兩個下拉式選單,第一個為地區(id: ddlArea),第二個顯示對應地區的縣市(id: ddlCounty)。


作法:
使用ASP.NET Ajax:
1. .NET 3.5已內建ASP.NET Ajax,若是更舊版本需自行import Ajax Extensions。
2. 從工具箱拉ScriptManager與UpdatePanel控制項,然後將ddlCounty放進UpdatePanel內,
     並設定Triggers為ddlArea,例:
xxx.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server" ScriptMode="Release" >
    </asp:ScriptManager>
<asp:DropDownList ID="ddlArea" runat="server" AutoPostBack="true" onselectedindexchanged="ddlArea_SelectedIndexChanged"></asp:DropDownList>
 <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
     <ContentTemplate>
         <asp:DropDownList ID="ddlCounty" runat="server"></asp:DropDownList>    
     </ContentTemplate>
     <Triggers>
          <asp:AsyncPostBackTrigger ControlID="ddlArea"
                                EventName="SelectedIndexChanged"></asp:AsyncPostBackTrigger>
     </Triggers>
 </asp:UpdatePanel>

xxx.aspx.cs
protected void ddlArea_SelectedIndexChanged(object sender, EventArgs e)
{
        if (this.ddlArea.SelectedIndex > 0)
        {
            DataTable dtCounty = 資料來源;
            this.ddlCounty.DataSource = dtCounty;
            this.ddlCounty.DataTextField = "County_Name";
            this.ddlCounty.DataValueField = "County_No";
            this.ddlCounty.DataBind();
        }
}


使用jQuery Ajax (後端使用webservice):
1. 在webservice新增webmethod供ajax存取,例:
//WebService.cs
public class AreaInfo
{
        public string AreaNo { get; set; }
        public string AreaName { get; set; }
}

public class CountyInfo
{
        public string CountyNo { get; set; }
        public string CountyName { get; set; }
}

[WebMethod]
public List<AreaInfo> LoadArea()
{
        List<AreaInfo> AreaInfo1 = new List<AreaInfo>();

        DataTable dtResult = 資料來源;
        if (dtResult != null && dtResult.Rows.Count > 0)
        {
            for (int i = 0; i < dtResult.Rows.Count; i++)
            {
                AreaInfo1.Add(new AreaInfo()
                {
                    AreaNo = dtResult.Rows[i]["Area_No"].ToString(),
                    AreaName = dtResult.Rows[i]["Area_Name"].ToString()
                });
            }
        }
        return AreaInfo1;
}

[WebMethod]
public List<CountyInfo> LoadCounty(string strAreaNo)
{
        List<CountyInfo> CountyInfo1 = new List<CountyInfo>();

        DataTable dtResult = 資料來源;

        if (dtResult != null && dtResult.Rows.Count > 0)
        {
            for (int i = 0; i < dtResult.Rows.Count; i++)
            {
                CountyInfo1.Add(new CountyInfo()
                {
                    CountyNo = dtResult.Rows[i]["County_No"].ToString(),
                    CountyName = dtResult.Rows[i]["County_Name"].ToString()
                });
            }
        }
        return CountyInfo1;
}

2. include jQuery library並使用jQuery.ajax跟後端要資料(回傳格式使用json),例:
//xxx.aspx
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
        $(document).ready(function() {
        $.ajax({
                type: 'post',
                contentType: "application/json; charset=utf-8",
                url: "WebService.asmx/LoadArea",
                data: "{}",
                dataType: "json",
                success: function(Result) {
                    $.each(Result.d, function(key, value) {
                        $("#ddlArea").append($("<option></option>").val(value.AreaNo).html(value.AreaName));
                    });
                },
                error: function() { alert('ajax fail'); }
            });
            $('#ddlArea').change(function() {
            $("#ddlCounty").find('option').remove();
                var ID = $(this).val();
                $.ajax({
                    type: 'post',
                    contentType: "application/json; charset=utf-8",
                    url: "WebService.asmx/LoadCounty",
                    data: "{strAreaNo:" + ID + "}",
                    dataType: "json",
                    success: function(Result) {
                        $.each(Result.d, function(key, value) {
                           $("#ddlCounty").append($("<option></option>").val(value.CountyNo).html(value.CountyName));
                        });
                    },
                    error: function() { alert('ajax fail'); }
                });
            });
        });
</script>

<asp:DropDownList ID="ddlArea" runat="server"></asp:DropDownList>
<asp:DropDownList ID="ddlCounty" runat="server"></asp:DropDownList>


參考資料:
http://stackoverflow.com/questions/10477476/why-0-in-textbox10-value-is-used-to-get-scalar-value-in-asp-net-control

http://www.dotblogs.com.tw/hatelove/archive/2009/12/22/jqueryajax.aspx
http://msdn.microsoft.com/zh-tw/dd310332.aspx#jQuery
http://www.dotblogs.com.tw/topcat/category/1656.aspx
http://pastie.org/2356308
http://social.msdn.microsoft.com/Forums/zh-TW/384800f1-d366-484e-bd30-aaeac5d07d85/aspnet-jqueryjqueryajaxashxaspxasmx?forum=236#9125942a-cc8a-41d5-981e-882fe0894f82
https://www.youtube.com/playlist?list=PLNPgPJ-90sSlwfSHvuyafzWJ8jQphAam0
http://www.codeproject.com/Tips/688228/Bind-Dropdownlist-in-ASP-NET-using-jQuery-AJAX
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

沒有留言:

張貼留言