惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
GbyAI
GbyAI
Engineering at Meta
Engineering at Meta
有赞技术团队
有赞技术团队
博客园 - 【当耐特】
H
Hackread – Cybersecurity News, Data Breaches, AI and More
WordPress大学
WordPress大学
博客园_首页
美团技术团队
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
小众软件
小众软件
J
Java Code Geeks
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
IT之家
IT之家
T
The Blog of Author Tim Ferriss
Microsoft Azure Blog
Microsoft Azure Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog
雷峰网
雷峰网
爱范儿
爱范儿

博客园 - Gordon Golden Shining

who am I inside of me STGenerator Released ObjectDataSource的Add-In Asp.net page lifecycle explain in msdn 我做的代码生成的工具的思路 (支持.NET2.0) Programming Haskell in Visual Studio.net 2003 C#/VB.Net converter A good book to read A possible way for testing threading/server application a break in .net 2.0 remoting WinXP sp2 and win 2003 does break com+/System.Transaction 2.0 You have to read this All about codes generation New tools box for year 2005 Recommend: IOC container must read article dynamic proxy how to How to implement AOP in .net My Wishlist for .net development some common used tips in web development
No refresh dropdownlist using xmlhttp callback
Gordon Golden Shining · 2005-06-10 · via 博客园 - Gordon Golden Shining

Recenly finish a simple drop down list loading with xmlhttp (or ajax), just post some codes for you use if you interested.
the codes mostly from this document:

http://dotnethero.com/hero/Selectionlists/Callback.aspx?nmx=6_4

Another way to do is using the ajax package, which encapsulate you everything. But I would like to show you how the xmlhttp works for no refresh postback.

In the aspx page, you need two javascript function:

function DoCallback(url, params){
   // params: string object to pass to the remote URL
   
   // Add some parameters to the query string
   var pageUrl = url + "?callback=true&param=" + params;

   // Initialize the XmlHttp object
    try {
        //Mozilla Browsers
        xmlRequest = new XMLHttpRequest();
    }
    catch (e) {
        try {
            //IE
            xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) {
            //Something else that won't work with this code...
            xmlRequest=false;
        }
    }
    // Post our XmlRequest and get our desired string
    xmlRequest.open("GET", pageUrl, false);
    xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlRequest.send(null);

    // Return the XmlHttp object
    return xmlRequest;
}

//--------------

function ShowModels()
{
    //Clear the options currently in the list
    for (x = document.Form1.usrSelection_lstModel.length; x >= 0; x = x - 1)
    {
        document.Form1.usrSelection_lstModel[x] = null;
    }
    //Add the select
    document.Form1.usrSelection_lstModel[0] = new Option("Select", "");
    //Get the value of the selected item
    var ManuID = document.Form1.usrSelection_lstMake.value;
    //Get data from the server
    var currenturl = location.href;
    var xml = DoCallback(currenturl, ManuID);
    //Place data in a string
    var Models = xml.responseText;
    //Split the string and place in an array
    modelArray = Models.split(",")
    //Loop through each item in the array and place the item in the Drop down list
    for(var i=0; i < modelArray.length; i++)
    {
        document.Form1.usrSelection_lstModel[document.Form1.usrSelection_lstModel.length] = new Option(modelArray[i], modelArray[i]);
    }
}

The first one is used to start one xmlhttp object and send parameter back to the url for server side call
showModel is used to parse the page string to list item and reload the dropdownlist item.

usrSelection_lstModel is the dropdownlist you want to dynamicly read.

usrSelection_lstMake is used to get the paramters.

the following two lines code in the showModel() function is used to get the current page url and send the parameter to codes behind and have the result back ready for list.

    var currenturl = location.href;
    var xml = DoCallback(currenturl, ManuID);

//---------------------------------------------

Client script is finished now, let us look at what need in the codes behind.

first need to add a Callback_PageLoad in the page_load event to do the callback related initialization.
    private void Page_Load(object sender, System.EventArgs e)
        {
            //callback related Initialize
            Callback_PageLoad();
        }

        private void Callback_PageLoad()
        {
            if (IsCallback())
                return;
       
            lstMake.Attributes.Add("onchange", "ShowModels()");                       
        }

        private bool IsCallback()
        {
            if (Request.QueryString["callback"] != null)
            {
                string param1 = Request.QueryString["param"].ToString();
                Response.Write(RaiseCallbackEvent(param1));
                Response.Flush();
                Response.End();
                return true;
            }
            else
                return false;
        }

callback_pageload is only need to check if it is callback action and return the callback server call result via response.

the last function is used to load the dropdownlist from a business component.
public string RaiseCallbackEvent(string eventArgument)
        {
            if (eventArgument.Equals(""))
                return "";

            int make = Convert.ToInt32(eventArgument);

            Schema.VehicleModelListDs ds = new VehicleModelListDs();
           ds = vehicleBL.GetModelList(make);

            StringBuilder sb = new StringBuilder();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                sb.Append(dr["Model"].ToString());
                sb.Append(",");
            }
            string ret = sb.ToString();
            if (ret.EndsWith(","))
                return ret.Substring(0, ret.Length-1);
            else
                return ret;
        }

One more thing need to be aware of is, because the dropdownlist is loaded in the client side now, so you have to
use Request["dropdownlistname"] to retrieve the value.

Also if you post back, the dropdownlist values which load from clientside won't be there because asp.net has no
its viewstate. what you need to do is to load the dropdownlist in page_load everytime, or you can cache the items
to be more efficient.

hope this is useful...