2008-09-17 21 views
5

初めて.NET UpdatePanelsで作業します。AJAX - サーバーに値を渡す方法

私は、FormViewコントロールのイベントを指し示すトリガーを持つupdatepanelを持っています。 UpdatePanelは、別のデータベースからの関連データを含むListViewを保持します。

UpdatePanelがリフレッシュされるとき、サーバー上でデータベースを照会するために、FormViewコントロールからの値が必要です。

私の人生にとって、私はそれらの値を取得する方法を見つけることができません。私がトリガしているイベントにはそれらがありますが、私はupdatepanelを非同期的にリフレッシュする必要があります。パネルのロードイベントに値を渡すにはどうすればよいですか?

この広告の主題はGoogleでグーグルであり、ここでは回答が得られないようです。リンクや説明が非常に参考になる。..

ジェフ

答えて

4

フォームデータを収集し、そのデータをASHXハンドラに送信するjavascript関数を作成します。 ASHXハンドラは何らかの作業を行い、応答を返すことができます。

これは、データベースを呼び出して、AJAX呼び出しを使用してグリッドにデータを設定する例です。 AJAX(プロトタイプ、ExtJSなど)を行うための優れたライブラリがありますが、これは未加工の取引です。このような

作品(私はこれもきれいであることをリファクタリングすることができますが、あなたのアイデアが十分に得ることができますを知っています)...

  • ユーザーは、
  • ユーザーは、検索ボタンをクリックし、検索ボックスにテキストを入力する
  • JavaScriptがフォームデータ、
  • JavascriptをASHXへのAJAX呼び出しを行い、
  • ASHXが要求を受信し、取得
  • ASHXクエリデータベース
  • ASHXはJSON/Javascript配列への応答を解析し、
  • ASHXは、応答は、
  • Javascriptが応答を受信した送信
  • javascriptの評価()のオブジェクトへの応答、繰り返し処理はオブジェクトプロパティを、グリッド

HTMLは次のようになりますを埋めるのjavascript

  • ...

    <html xmlns="http://www.w3.org/1999/xhtml" > 
    <head runat="server"> 
        <title>Untitled Page</title> 
        <script type="text/javascript" src="AjaxHelper.js"></script> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
        <div> 
         <asp:TextBox ID="txtSearchValue" runat="server"></asp:TextBox> 
         <input id="btnSearch" type="button" value="Search by partial full name" onclick="doSearch()"/> 
    
         <igtbl:ultrawebgrid id="uwgUsers" runat="server" 
    //infragistics grid crap 
          </igtbl:ultrawebgrid>--%> 
        </div> 
        </form> 
    </body> 
    </html> 
    

    クリックの火災は、このようになります。スクリプト...

    //this is tied to the button click. It takes care of input cleanup and calling the AJAX method 
    function doSearch(){ 
        var eleVal; 
        var eleBtn; 
        eleVal = document.getElementById('txtSearchValue').value; 
        eleBtn = document.getElementById('btnSearch'); 
        eleVal = trim(eleVal); 
        if (eleVal.length > 0) { 
         eleBtn.value = 'Searching...'; 
         eleBtn.disabled = true; 
         refreshGridData(eleVal); 
        } 
        else { 
         alert("Please enter a value to search with. Unabated searches are not permitted."); 
        } 
    } 
    
    //This is the function that will go out and get the data and call load the Grid on AJAX call 
    //return. 
    function refreshGridData(searchString){ 
    
        if (searchString =='undefined'){ 
         searchString = ""; 
        } 
    
        var xhr; 
        var gridData; 
        var url; 
    
        url = "DefaultHandler.ashx?partialUserFullName=" + escape(searchString); 
        xhr = GetXMLHttpRequestObject(); 
    
        xhr.onreadystatechange = function() { 
         if (xhr.readystate==4) { 
          gridData = eval(xhr.responseText); 
          if (gridData.length > 0) { 
           //clear and fill the grid 
           clearAndPopulateGrid(gridData); 
          } 
          else { 
           //display appropriate message 
          } 
         } //if (xhr.readystate==4) { 
        } //xhr.onreadystatechange = function() { 
    
        xhr.open("GET", url, true); 
        xhr.send(null); 
    } 
    
    //this does the grid clearing and population, and enables the search button when complete. 
    function clearAndPopulateGrid(jsonObject) { 
    
        var grid = igtbl_getGridById('uwgUsers'); 
        var eleBtn; 
        eleBtn = document.getElementById('btnSearch'); 
    
        //clear the rows 
        for (x = grid.Rows.length; x >= 0; x--) { 
         grid.Rows.remove(x, false); 
        } 
    
        //add the new ones 
        for (x = 0; x < jsonObject.length; x++) { 
         var newRow = igtbl_addNew(grid.Id, 0, false, false); 
         //the cells should not be referenced by index value, so a name lookup should be implemented 
         newRow.getCell(0).setValue(jsonObject[x][1]); 
         newRow.getCell(1).setValue(jsonObject[x][2]); 
         newRow.getCell(2).setValue(jsonObject[x][3]); 
        } 
    
        grid = null; 
    
        eleBtn.disabled = false; 
        eleBtn.value = "Search by partial full name"; 
    } 
    
    
    // this function will return the XMLHttpRequest Object for the current browser 
    function GetXMLHttpRequestObject() { 
    
        var XHR; //the object to return 
        var ua = navigator.userAgent.toLowerCase(); //gets the useragent text 
        try 
        { 
         //determine the browser type 
         if (!window.ActiveXObject) 
         { //Non IE Browsers 
          XHR = new XMLHttpRequest(); 
         } 
         else 
         { 
          if (ua.indexOf('msie 5') == -1) 
          { //IE 5.x 
           XHR = new ActiveXObject("Msxml2.XMLHTTP"); 
          } 
          else 
          { //IE 6.x and up 
           XHR = new ActiveXObject("Microsoft.XMLHTTP"); 
          } 
         } //end if (!window.ActiveXObject) 
    
         if (XHR == null) 
         { 
          throw "Unable to instantiate the XMLHTTPRequest object."; 
         } 
        } 
        catch (e) 
        { 
         alert("This browser does not appear to support AJAX functionality. error: " + e.name 
           + " description: " + e.message); 
        } 
        return XHR; 
    } //end function GetXMLHttpRequestObject() 
    
    function trim(stringToTrim){ 
        return stringToTrim.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); 
    } 
    

    そして、良いニュースだろうASHXハンドラは次のようになります....

    Imports System.Web 
    Imports System.Web.Services 
    Imports System.Data 
    Imports System.Data.SqlClient 
    
    Public Class DefaultHandler 
        Implements System.Web.IHttpHandler 
    
        Private Const CONN_STRING As String = "Data Source=;Initial Catalog=;User ID=;Password=;" 
    
        Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest 
    
         context.Response.ContentType = "text/plain" 
         context.Response.Expires = -1 
    
         Dim strPartialUserName As String 
         Dim strReturnValue As String = String.Empty 
    
         If context.Request.QueryString("partialUserFullName") Is Nothing = False Then 
          strPartialUserName = context.Request.QueryString("partialUserFullName").ToString() 
    
          If String.IsNullOrEmpty(strPartialUserName) = False Then 
           strReturnValue = SearchAndReturnJSResult(strPartialUserName) 
          End If 
         End If 
    
         context.Response.Write(strReturnValue) 
    
        End Sub 
    
    
        Private Function SearchAndReturnJSResult(ByVal partialUserName As String) As String 
    
         Dim strReturnValue As New StringBuilder() 
         Dim conn As SqlConnection 
         Dim strSQL As New StringBuilder() 
         Dim objParam As SqlParameter 
         Dim da As SqlDataAdapter 
         Dim ds As New DataSet() 
         Dim dr As DataRow 
    
         'define sql 
         strSQL.Append(" SELECT ") 
         strSQL.Append("  [id] ") 
         strSQL.Append("  ,([first_name] + ' ' + [last_name]) ") 
         strSQL.Append("  ,[email] ") 
         strSQL.Append(" FROM [person] (NOLOCK) ") 
         strSQL.Append(" WHERE [last_name] LIKE @lastName") 
    
         'clean up the partial user name for use in a like search 
         If partialUserName.EndsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then 
          partialUserName = partialUserName & "%" 
         End If 
    
         If partialUserName.StartsWith("%", StringComparison.InvariantCultureIgnoreCase) = False Then 
          partialUserName = partialUserName.Insert(0, "%") 
         End If 
    
         'create the oledb parameter... parameterized queries perform far better on repeatable 
         'operations 
         objParam = New SqlParameter("@lastName", SqlDbType.VarChar, 100) 
         objParam.Value = partialUserName 
    
         conn = New SqlConnection(CONN_STRING) 
         da = New SqlDataAdapter(strSQL.ToString(), conn) 
         da.SelectCommand.Parameters.Add(objParam) 
    
         Try 'to get a dataset. 
          da.Fill(ds) 
         Catch sqlex As SqlException 
          'Throw an appropriate exception if you can add details that will help understand the problem. 
          Throw New DataException("Unable to retrieve the results from the user search.", sqlex) 
         Finally 
          If conn.State = ConnectionState.Open Then 
           conn.Close() 
          End If 
          conn.Dispose() 
          da.Dispose() 
         End Try 
    
         'make sure we have a return value 
         If ds Is Nothing OrElse ds.Tables(0) Is Nothing OrElse ds.Tables(0).Rows.Count <= 0 Then 
          Return String.Empty 
         End If 
    
         'This converts the table into JS array. 
         strReturnValue.Append("[") 
    
         For Each dr In ds.Tables(0).Rows 
          strReturnValue.Append("['" & CStr(dr("username")) & "','" & CStr(dr("userfullname")) & "','" & CStr(dr("useremail")) & "'],") 
         Next 
    
         strReturnValue.Remove(strReturnValue.Length - 1, 1) 
         strReturnValue.Append("]") 
    
         'de-allocate what can be deallocated. Setting to Nothing for smaller types may 
         'incur performance hit because of a forced allocation to nothing before they are deallocated 
         'by garbage collection. 
         ds.Dispose() 
         strSQL.Length = 0 
    
         Return strReturnValue.ToString() 
    
        End Function 
    
    
        ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable 
         Get 
          Return False 
         End Get 
        End Property 
    
    End Class 
    
  • 1

    は、リクエストとレスポンス で探して...

    • を試してみてください。
    • ...あなたは をしたい値は多分ちょうどあなたがそれらを 期待しているされていない場所かどうかを確認するために時計や即時 ウィンドウでこのロード()メソッドにブレークポイント を設定して、私を照会したり、 ?
    • ...(それぞれのコントロールでControl for Me/This.Controlsに) を入れ、繰り返される各コントロールを調べて、あなたが期待するコントロールを取得しているかどうかを確認してください。
    • ...そのSenderまたはEventArgsにはありませんか?

    アップデートパネルを使用しないでください。これらのパネルは、価値があるよりも多くのトラブルを引き起こすことがあります。通常のAJAXを使用してそれを行うのは、より速く、頭痛も少ないかもしれません。

    1

    UpdatePanelを使用している場合は、両方のコントロールがパネル内にあることを確認してください。

    +0

    ミッチェル、。私はあなたが提案したことをしましたが、パネルのロードイベントで必要な値がどのように表示されるかはまだ不明です。もっと教えていただけますか? – jlembke

    関連する問題