现在的位置: 首页 > 综合 > 正文

ASP.NET AJAX in Action—Web Service与updatepanel

2013年03月22日 ⁄ 综合 ⁄ 共 7785字 ⁄ 字号 评论关闭

简单的异步请求:

 

代码

    function makeRequest(){    
        
var request = new Sys.Net.WebRequest();
        request.set_url(
"Hello.txt");
        request.add_completed(onRequestCompleted);
        request.invoke();    
    }
    
function onRequestCompleted(executor, args){  
          
        
var e = executor.checkError();   
        
if (e)
        {
            updateResults(
"error: " + e.message);
        }
        
else
        {
            updateResults(executor.get_responseData());
        }             
    }
    
function updateResults(update){    
        
var results = $get('responseData');
        
if (results.innerHTML.length > 0)
            results.innerHTML 
+= "<br />";
            
        results.innerHTML 
+= update;        
    }
    Sys.Net.WebRequestExecutor.prototype.checkError 
= function() {
        
        
// Status Code Range    Meaning
        // 100-199    Informational status codes. These status codes will not normally arise during ASP.NET Ajax development and can be ignored.
        // 200-299    The request was received and successfully processed.
        // 300-399    The request needs to be redirected. The most common code in this range is HTTP status code 302 which is sent when Response.Redirect is called from ASP.NET code.
        // 400-499    The request contains an error. A Common error code is 404 which indicates that the resource (file) was not found on the server.
        // 500-599    The request was valid but the server failed to process the request. The most common error code in this range is 500, which is returned by ASP.NET when an exception occurs during request processing.                        
        
        
var e = null;
        
        
if (this.get_aborted()) {
            e 
= Error.create('Request Aborted.'
                       { name : 
'RequestAbortedError' });
        }
        
else if (this.get_timedOut()) {
            e 
= Error.create('Request timed out.'
                       { name : 
'RequestTimeoutError' } );
        }
        
else {
            
var statusCode;
            
try {
                statusCode 
= this.get_statusCode();
            }
            
catch(e) {
                statusCode 
= 0;
            }
            
            
if (statusCode < 100 || statusCode >= 600) {
                e 
= Error.create('Connection Error.'
                                 {name : 
'ConnectionError' });   
            }
            
else if ((statusCode < 200|| (statusCode >= 300)) {
                e 
= Error.create('HTTP Error.'
                                 { name : 
'HTTPError'
                                   
"statusCode" : statusCode, 
                                   statusText : 
this.get_statusText() } );
            }    
        }
        
        
return e;
    
    }

 

调用Web 服务:

 

代码

  <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
   
<Services>
     
<asp:ServiceReference Path="StarbucksService.asmx" InlineScript="true" />
   </Services>
  </asp:ScriptManager>

  
function getLocations(){    
    
var zip = $get("Location").value;
    AspNetAjaxInAction.StarbucksService.GetLocationCount(zip, onGetLocationSuccess, onGetLocationFailure, 
"<%= DateTime.Now %>");    //参数,成功回调,异常回调,回送Context供回调函数使用
  }

  function onGetLocationSuccess(result, context, methodName){
    $get(
"NumLocations").innerHTML = result + " location(s) found.";    //返回值,Context,调用的方法名
  }

  function onGetLocationFailure(error, context, methodName){
    
var errorMessage = error.get_message();
    $get(
"NumLocations").innerHTML = errorMessage;
  }

 

 

 使用服务器对象:

 

代码

    //后台方法,需要  <asp:ScriptManager ... EnablePageMethods="True">支持
   [WebMethod]   
    public static string HelloEmployee(AspNetAjaxInAction.Employee emp)
    {
        
return string.Format("Hello {0} {1}.", emp.First, emp.Last);
    }

    function createEmployee(){                   
        
var emp1 = new AspNetAjaxInAction.Employee();
        emp1.First 
= "Frank";
        emp1.Last 
= "Rizzo";        
        emp1.Title 
= "Principal";
        
        PageMethods.HelloEmployee(emp1, onHelloEmployeeSuccess);       //前台直接使用 PageMethods.HelloEmployee
    }

    function onHelloEmployeeSuccess(result, context, methodName){
        alert(result);
    }

  function getDeals(){
    AspNetAjaxInAction.StarbucksService.GetDeals(onGetDealsSuccess, onGetDealsFailure, 
"context"1000);
  }
  
  
function onGetDealsSuccess(result, context, methodName){
    
    Sys.Debug.traceDump(result);
    
    
var sb = new Sys.StringBuilder();    
    
for (var i = 0; i < result.length; i++){        //服务器返回List<>,以JSON格式获取
        var bev = result[i];
        sb.append(bev.Name 
+ " - ");
        sb.append(bev.Description 
+ " - ");
        sb.append(bev.Cost 
+ "<br />");        
    }    
    
    $get(
"Deals").innerHTML = sb.toString();
  }

 

 调用ASP.NET的用户验证服务:

 

代码

//配置支持
    <system.web.extensions>
        
<scripting>
            
<webServices>
                
<authenticationService enabled="true" requireSSL="false"/>
                <profileService enabled="true" readAccessProperties="AutoSavedMessage.Subject,                                 AutoSavedMessage.Text,                                 Address1,                                 Address2,                                 City,                                 State,                                 Zip" writeAccessProperties="AutoSavedMessage.Subject,                                  AutoSavedMessage.Text,                                                                   Address1,                                  Address2,                                  City,                                  State,                                  Zip"/>
            </webServices>
        </scripting>
    </system.web.extensions>        

//登录
        var username = $get('username');
        
var password = $get('password');                                              
        Sys.Services.AuthenticationService.login(username.value,
                                                password.value,
                                                
false,
                                                
null,
                                                
"Secure/ContactInformation.aspx",
                                                
null,
                                                onLoginFailed,
                                                
"User Context");   
     
//注销
     function logoutUser(){
        $get(
"updating").style.display = "block";
        $get(
"message").innerHTML = "Logging out...";
        Sys.Services.AuthenticationService.logout(
null, onLogoutCompleted, onLogoutFailed, null);
    }

     //修改资料
    function saveProfile(){
        
        
var addr1 = $get("address1").value;
        
var addr2 = $get("address2").value;
        
var city = $get("city").value;
        
var state = $get("state").value;
        
var zip = $get("zip").value;
        
        Sys.Services.ProfileService.properties.Address1 
= addr1;
        Sys.Services.ProfileService.properties.Address2 
= addr2;
        Sys.Services.ProfileService.properties.City 
= city;
        Sys.Services.ProfileService.properties.State 
= state;
        Sys.Services.ProfileService.properties.Zip 
= zip;        
        Sys.Services.ProfileService.save(
null, onSaveCompleted, onSaveFailed, null);        
    }

 

 PageRequestManager在启用部分更新的时候,管理浏览器上发生的异步回送和更新:

initializeRequest事件:可以在这个事件中截获某事件;

beginRequest事件:将要开始异步请求,UpdateProgress就是在这里添加提示的;

pageLoading事件:得到服务器的响应信息,可以在这里检查来自服务器的数据;

pageLoaded事件:每次加载页面都会触发该事件,标识与服务器通信结束,可以在这里区分常规请求与异步请求;

load事件:Application在这个时候做很多事情;

endRequest事件:一次请求结束,会显示请求的结果,比如出现的异常。

 

UpdatePanel在更新HTML之前会花很多时候去做避免内存泄漏的检查,如果页面上异步更新的元素没有与MS AJAX组件或者行为关联,可以解除其内控件与父节点的关联,绕过检查内存泄漏的环节:

 

代码

var pageRequestManager=Sys.WebForms.PageRequestManager.getInstance();
pageRequestManager.add_pageLoading(onPageLoading);

function onPageLoading(sender,e){
    
var gv=$get("GridView1");
    gv.parentNode.removeNode(gv);
}

 

 

抱歉!评论已关闭.