博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
No refresh dropdownlist using xmlhttp callback
阅读量:4992 次
发布时间:2019-06-12

本文共 4435 字,大约阅读时间需要 14 分钟。

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...

转载于:https://www.cnblogs.com/gozh2002/archive/2005/06/10/171526.html

你可能感兴趣的文章
unity回调函数范例
查看>>
linux下给php安装curl、gd(ubuntu)
查看>>
Java自带的Logger使用-代码摘要
查看>>
Java设计模式系列 — 构造器模式
查看>>
MySQL执行计划explain的key_len解析
查看>>
Windows Phone开发(9):关于页面状态 转:http://blog.csdn.net/tcjiaan/article/details/7292160...
查看>>
android 通过数组,流播放声音的方法
查看>>
Spring入门篇
查看>>
JAVA遇见HTML——JSP篇(JSP状态管理)
查看>>
启动eclipse出现错误Java was started but returned exit =一个数字
查看>>
myBatis模糊查找
查看>>
数据结构与算法之五 链接列表
查看>>
java 对象数组
查看>>
设计模式读书笔记-单件模式(创建型模式)
查看>>
Oracle——热备份
查看>>
Vue路由history模式踩坑记录:nginx配置解决404问题
查看>>
c# 多张图片合成一张图片
查看>>
使用SQL Server 2008的事务日志传送功能备份数据库(logshiping)
查看>>
AngularJS多个ng-app只解析第一个的问题
查看>>
强制修改常量的值
查看>>