返回首页

{A}
{S0}简介
这是一个非常简单的Web应用程序和用户友好的技术,实现无刷新页面级联菜单。
您不知道Ajax功能,只是在CodePlex上下载AJAX Control Toolkit中,并按照本文所述的步骤。当你有两个DropDownList,他们都是等,每一个注册页面,您要保存有关用户的故乡信息,如国家和市有关。当您选择从第一个DropDownList(国家)的某些行,你会期望,无需刷新页面选择行的第二个DropDownList(市)要筛选。本文展示了一个非常简单和用户友好的解决方案,可用于在Web应用程序。背景:什么是AJAX Control Toolkit中?
ASP.NET AJAX控件工具包是一个开源项目的Microsoft ASP.NET AJAX框架之上,并包含超过30个控制,使您可以轻松地创建丰富,交互式网页。如果你想了解它的更多信息,请访问。使用代码
第一步是从下载AJAX Control Toolkit中。
AJAX Control Toolkit中复制到Bin文件夹右键点击解决方案,选择"添加引用"浏览"选项卡,双击Bin文件夹中,和AJAX Control Toolkit中双击,然后在生成菜单上,单击重建。数据库
创建一个数据库和它命名为quot; Dbquot;下面是查询,以创建所需的表:Visual Studio 2008中 - NET 3.5
创建一个网站,它命名为级联菜单。创建一个Web表单,并命名它CascadingDropDown.aspx。在HTML视图,编写下面的代码。在本节中的代码是一个小的C#和VB之间的不同。如果你是一个VB程序员,在第一线的页面标签修改两个部分:LANGUAGE ="; VBquot";的CodeFile ="; CascadingDropDown.aspx.vbquot";{C}
对于VB:创建Web服务:解决方案GT;右击GT;添加新项GT; Web服务GT。名称:Cascading.asmx。语言:Visual Basic中。到GT的App_Code GT; Cascading.vb。

' (c) Copyright Microsoft Corporation.

' This source is subject to the Microsoft Public License.

' See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.

' All other rights reserved.

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

Imports System.Collections.Generic

Imports AjaxControlToolkit

Imports System.Data

Imports System.Data.SqlClient

Imports System.Text.RegularExpressions

Imports System.Collections.Specialized

Imports System.Xml



' To allow this Web Service to be called from script,

' using ASP.NET AJAX, uncomment the following line.

<System.Web.Script.Services.ScriptService()> _

<WebService(Namespace:="http://tempuri.org/")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _

Public Class Cascading

    Inherits System.Web.Services.WebService

    Dim cn As New SqlClient.SqlConnection()

    Dim ds As New DataSet

    Dim dt As New DataTable



<WebMethod()> _

Public Function GetCountries(ByVal knownCategoryValues As String, _

       ByVal category As String) As CascadingDropDownNameValue()



    'ADO.Net

    Dim strCn As String = "data source=.;Initial Catalog=Db;Integrated Security=True"



    cn.ConnectionString = strCn

    Dim cmd As New SqlClient.SqlCommand

    cmd.Connection = cn

    cmd.CommandType = CommandType.Text

    cmd.CommandText = "select * from tblCountry"



    Try

        cn.Open()

        cmd.ExecuteNonQuery()

        Dim da As New SqlDataAdapter(cmd)

        da.Fill(ds)

    Catch ex As Exception

    Finally

        cn.Close()

    End Try



    dt = ds.Tables(0)

    Dim CountryValues As New List(Of CascadingDropDownNameValue)()



    For Each row As DataRow In dt.Rows

       CountryValues.Add(New CascadingDropDownNameValue(row("Country").ToString(), _

                         row("IDC").ToString()))

    Next



    Return CountryValues.ToArray()



End Function



<WebMethod()> _

Public Function GetCities(ByVal knownCategoryValues As String, _

                ByVal category As String) As CascadingDropDownNameValue()



    Dim kv As StringDictionary = _

        CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)

    'ContainsKey("Country") is one of property in Ajaxcontroltoolkit

    Dim countryId As Integer



    If ((Not kv.ContainsKey("Country")) Or _

        (Not Int32.TryParse(kv("Country"), countryId))) Then

        Return Nothing

    End If



    'ADO.Net

    Dim strCn As String = "data source=.;Initial Catalog=Db;Integrated Security=True"

    cn.ConnectionString = strCn

    Dim cmd As New SqlClient.SqlCommand

    cmd.Connection = cn

    '-----I Defined a parameter instead of passing value 

    '               directly to prevent sql injection--------'

    cmd.CommandText = "select * from tblCity where CountryID=@myParameter Order by City"

    cmd.Parameters.AddWithValue("@myParameter", countryId.ToString())



    Try

        cn.Open()

        cmd.ExecuteNonQuery()

        Dim da As New SqlDataAdapter(cmd)

        da.Fill(ds)

    Catch ex As Exception

    Finally

        cn.Close()

    End Try



    dt = ds.Tables(0)

    Dim CityValues As New List(Of CascadingDropDownNameValue)()



    For Each row As DataRow In dt.Rows

       CityValues.Add(New CascadingDropDownNameValue(row("City").ToString(), _

                      row("ID").ToString()))

    Next



    Return CityValues.ToArray()



End Function



End Class

C#Web服务解决方案:GT;右击GT;添加新项GT; Web服务GT。名称:Cascading.asmx。语言:C#。到GT的App_Code GT; Cascading.cs。
// (c) Copyright Microsoft Corporation.

// This source is subject to the Microsoft Public License.



// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.

// All other rights reserved.

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Collections.Generic;

using AjaxControlToolkit;

using System.Data;

using System.Data.SqlClient;

using System.Text.RegularExpressions;

using System.Collections.Specialized;

using System.Xml;



///<summary>

/// Summary description for Cascading

///</summary>



[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script,

// using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]

public class Cascading : System.Web.Services.WebService {



    public Cascading () {

        //Uncomment the following line if using designed components

        //InitializeComponent();

    }



    [WebMethod]

    public CascadingDropDownNameValue[] GetCountries(string knownCategoryValues, 

                                        string category)

    {

        //ADO.Net

        SqlConnection cn =new SqlConnection();

        DataSet ds = new DataSet();

        DataTable    dt = new DataTable();

        string strCn = "data source=.;Initial Catalog=Db;Integrated Security=True";

        cn.ConnectionString = strCn;

        SqlCommand cmd = new SqlCommand();

        cmd.Connection = cn;

        cmd.CommandType = CommandType.Text;

        cmd.CommandText = "select * from tblCountry";



        try

        {

            cn.Open();

            cmd.ExecuteNonQuery();

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(ds);

        }

        catch

        {

        }

        finally

        {

            cn.Close();

        }

        dt = ds.Tables[0];



        List<CascadingDropDownNameValue> CountryValues = 

                    new List<CascadingDropDownNameValue>();

        foreach (DataRow row   in dt.Rows)

        {

            CountryValues.Add(new CascadingDropDownNameValue(

              row["Country"].ToString(), row["IDC"].ToString()));

        }



        return CountryValues.ToArray();

    }



    [WebMethod]

    public CascadingDropDownNameValue[] GetCities(string knownCategoryValues, 

                                                  string category)

    {

        StringDictionary kv = 

          CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);



        //'ContainsKey("Country") is one of property in Ajaxcontroltoolkit

        int countryId;



        countryId = System.Convert.ToInt32(kv["Country"]);



        //ADO.Net

        SqlConnection cn = new SqlConnection();

        DataSet ds = new DataSet();

        DataTable    dt = new DataTable();

        string strCn = 

          "data source=.;Initial Catalog=Db;Integrated Security=True";



        cn.ConnectionString = strCn;

        SqlCommand cmd = new SqlCommand();



        cmd.Connection = cn;

        cmd.CommandType = CommandType.Text;

        //-----I Defined a parameter instead of passing value 

        //     directly to prevent sql injection--------//



        cmd.CommandText = "select * from tblCity where CountryID=@myParameter Order by City";

        cmd.Parameters.AddWithValue("@myParameter", countryId.ToString());

        try

        {

            cn.Open();

            cmd.ExecuteNonQuery();

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            da.Fill(ds);

        }

        catch

        {

        }

        finally

        {

            cn.Close();

        }

        dt = ds.Tables[0];



        List<CascadingDropDownNameValue> CityValues = 

                  new List<CascadingDropDownNameValue>();

        foreach (DataRow row   in dt.Rows)

        {

            CityValues.Add(new CascadingDropDownNameValue(

               row["City"].ToString(), row["ID"].ToString()));

        }

        return CityValues.ToArray();

    }

}

GetCountries和GetCities两个函数,得到两个字符串参数:knownCategoryValues​​和类别。他们有一个输出,这是一个字符串数组:CascadingDropDownNameValue。在GetCountries功能,国家DropDownList的填充:我们连接到数据库,并使用ADO.NET执行查询,然后在foreach循环中,填充的DropDownList。当您选择某一列(在上述例子中,一个国家如美国),knownCategoryValues​​将等于quot;国家:1quot;,这意味着类是国家和knownCategoryValues​​是quot; 1quot; 1,是美国在数据库中的ID。 GetCities功能,填补城市的DropDownList和过滤knownCategoryValues​​,这是quot; 1quot,在这种情况下。在Web窗体中,我指定ParentControlID ="; ddListCountryquot; CascadingCity,所以父是国家和城市将由国家ID过滤。此外,我定义了一个参数,而不是直接传递价值,以防止SQL注入。尝试演示一步一步转到和下载AJAX Control Toolkit中的文件。复制的文件夹quot; AjaxControlToolkit.Dllquot;及其所有依赖,它们是18个对象,你在网站的Bin文件夹(C:\层叠\斌)。右键单击解决方案,然后选择"刷新",然后点击右键再次单击添加引用。然后在"浏览"选项卡,双击Bin文件夹,双击上ajaxcontroltoolkit。在生成菜单上的GT;单击重建。 创建数据库和表像上面,并添加一些常用词的行。 创建一个Web表单,并命名它CascadingDropDown.aspx。在HTML视图,写一些像上面的代码。 (这应该是我的代码完全一样,因为这部分是大小写敏感的。)创建一个Web服务解决方案GT;右击GT;添加新项GT; Web服务GT;名称:Cascading.asmx。语言:C#或VB。 GT,GT的App_Code; Cascading.cs或Cascading.vb。如果你是一个VB程序员,使用VB范例,否则用C#范例。运行程序,选择一个国家如美国,你会看到一个在该国的城市如底特律或纽约市的清单。反馈
感觉自由离开任何对本文的反馈,这是一个很高兴看到您的意见和表决有关此代码。如果您有任何问题,请不要犹豫,问我在这里。

回答

评论会员:quentininsa 时间:2012/02/04
我需要做同样的事情在Net4.0使用MVC3和jQuery使人们有可能

建立一个像下面的
单独的脚本

$(function () {

    /* -- Cascading dropdowns -----------------

    data-action = "testing"

    data-child  = "childcontrol"

    ---------------------------------------- */

    $(":input[data-child]").change(function () {

        var currVal = $(this).val();

        var _action = $(this).attr("data-action");

        var _child = $(this).attr("data-child");

 

        var childSelect = $('#' + _child);

        childSelect.empty();

        childSelect.append($('<option/>', { value: "--All--", text: "--All--" }));

 

        if (currVal != null && currVal != '') {

            $.getJSON(_action, { selectedVal: currVal }, function (ChildData) {

                

                $.each(ChildData, function (index, sourceVal) {

                    childSelect.append($('<option/>', {

                        value: sourceVal.value,

                        text: sourceVal.text

                    }));

                });

            });

        }

    });

})


然后,在我看来,我使用:


...

 

<div class="editor-field">

  @Html.DropDownListFor(model => model.StaffBranchID, new SelectList ViewBag.Branches, "BranchID", "BranchName"), "-- Select --", new { data_action="getDivisions", data_child="StaffDivisionID" })

            @Html.ValidationMessageFor(model => model.StaffBranchID)

        </div>

...


data_action ="getDivisions"是在控制器上的行动 data_child ="StaffDivisionID"是控制,以取代结果。
我的行动看起来像这样:

[HttpGet]

public ActionResult getDivisionStaff(Guid selectedVal)

{

  return Json(db.StaffListByDivision(selectedVal).Select(x => new { value=x.StaffID, text=x.StaffFullName}), JsonRequestBehavior.AllowGet);

}
我有几个DropDownList控件上有相同的看法,联系起来的方式和他们所有的工作像一个魅力!
评论会员:MahsaHassankashi 时间:2012/02/04
不错的主意
优秀{S2}
评论会员:shaheen_mix 时间:2012/02/04
真的很好
评论会员:MahsaHassankashi 时间:2012/02/04

评论会员:米哈伊Maerean 时间:2012/02/04
这行代码是受教科书:
cmd.CommandText ="SELECT *从tblCity CountryID ="countryId.ToString()"市令";

请在代码注释中提到,此行必须改变网站去住(例如参数化查询)。越早后,每一个网站,尝试对基本的SQL注入(乐趣或利润)的游客。

而且在所有不好笑,当它发生。
米哈伊
评论会员:MahsaHassankashi 时间:2012/02/04
您好亲爱的米哈伊,我的文件是真实的,我写在HTML呢!!顺便说,我会尽快真正
感谢您的意见{S2}
评论会员:。阿伦Navasartian 时间:2012/02/04
尼斯
评论会员:MahsaHassankashi 时间:2012/02/04
亲爱的阿伦,谢谢
评论会员:cmacd12 时间:2012/02/04
除....乡亲"密歇根州"可能是您的拼写..... Mishigan恼火!
只是给你一个困难时期。

再次感谢!
"我们这里是失败的沟通。" - 船长
评论会员:MahsaHassankashi 时间:2012/02/04
您好亲爱的,我从密歇根州人的错误道歉,
ASAP的,我会改变图片,我不知道它{七}
评论会员:alipour2007 时间:2012/02/04

评论会员:MahsaHassankashi 时间:2012/02/04
谢谢阿里{S2}
评论会员:SunasaraImdadhusen 时间:2012/02/04
喜{BR }Mahsa,

干得好,你做,但你应该提供一些额外的普通工作从CodeProject上得到更多的赞赏。{S2}
我的投票5!


Imdadhusen sunaSaRa Imdadhusen
91 99095 44184
评论会员:MahsaHassankashi 时间:2012/02/04
您好亲爱的Sunasara
你说得对,我试着尽我所能。
在不久的将来,我会发布一些比我以前的文章强的文章。
评论会员:SunasaraImdadhusen 时间:2012/02/04

Mahsa,

我很高兴与您的肯定态度。继续努力吧{S2}


Imdadhusen sunaSaRa Imdadhusen
91 99095 44184
评论会员:Rhuros 时间:2012/02/04
良好的工作... ...
评论会员:MahsaHassankashi 时间:2012/02/04
谢谢Rhuros
评论会员:MahsaHassankashi 时间:2012/02/04
好,继续。 {S2}
我爱的T - SQL
"不要折磨自己,让生命为你做。"
如果我的文章可以帮助你请保存投票我的帖子我的时间。


上周五,7月8日,2011 7:35
修改
评论会员:velsantosh 时间:2012/02/04
`S你真好
感谢
评论会员:MahsaHassankashi 时间:2012/02/04
创意佳
评论会员:Anuj特里帕蒂 时间:2012/02/04
谢谢velsantosh
评论会员:MahsaHassankashi 时间:2012/02/04
尼斯
评论会员:Tohid阿齐兹 时间:2012/02/04
感谢Anuj {S17 }
评论会员:MahsaHassankashi 时间:2012/02/04
好文章,很高兴见到波斯怪才发表文章中的代码项目
Tohid艾则孜