문제

.NET에서 UpdatePanel을 처음 사용합니다.

FormView 컨트롤의 이벤트를 가리키는 트리거가 있는 업데이트 패널이 있습니다.UpdatePanel은 별도 데이터베이스의 관련 데이터가 포함된 ListView를 보유합니다.

UpdatePanel이 새로 고쳐질 때 서버에서 데이터베이스를 쿼리하는 데 사용할 수 있도록 FormView 컨트롤의 값이 필요합니다.

평생 동안 나는 그 가치를 얻는 방법을 알 수 없습니다.내가 트리거하는 이벤트에는 이러한 항목이 있지만 업데이트 패널을 비동기식으로 새로 고치기를 원합니다.패널의 로드 이벤트에 값을 어떻게 전달합니까?

이 광고 메스꺼움을 Google에서 검색했는데 여기서 답변을 얻을 수 없는 것 같습니다.링크나 설명을 주시면 큰 도움이 될 것 같습니다..

제프

도움이 되었습니까?

해결책

양식 데이터 조각을 수집하는 자바스크립트 함수를 만든 다음 해당 데이터를 ASHX 핸들러로 보냅니다.ASHX 핸들러는 몇 가지 작업을 수행하고 응답으로 응답할 수 있습니다.

이것은 AJAX 호출을 사용하여 그리드를 채우기 위해 데이터베이스를 호출하는 예제입니다.AJAX(프로토타입, ExtJS 등)를 수행하기 위한 더 나은 라이브러리가 있지만 이것은 원시적인 거래입니다.(나 알다 이는 더 깔끔하게 리팩토링될 수 있지만 아이디어를 충분히 얻을 수 있습니다.)

다음과 같이 작동합니다 ...

  • 사용자가 검색창에 텍스트를 입력하고,
  • 사용자가 검색 버튼을 클릭하면,
  • JavaScript는 양식 데이터를 가져옵니다.
  • javascript는 ASHX에 대한 ajax 호출을 수행합니다.
  • ASHX가 요청을 수신하고,
  • ASHX 쿼리 데이터베이스,
  • ASHX는 응답을 JSON/Javascript 배열로 구문 분석합니다.
  • ASHX가 응답을 보냅니다.
  • 자바스크립트가 응답을 받습니다.
  • 객체에 대한 javascript Eval()의 응답,
  • 자바스크립트는 객체 속성을 반복하고 그리드를 채웁니다.

HTML은 다음과 같습니다 ...

<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

다른 팁

노력하다

  • ... 요청과 응답을 찾고 있습니다.
  • ... load () 메소드에서 중단 점을 설정하고 시계 또는 즉각적인 창에서 저를 쿼리하여 원하는 값이 예상되는 곳이 아닌지 확인하십시오.
  • ... 각 CTL에 대해 (각 CTL에 대해 나/this.controls의 제어)를 넣고 반복되는 각 컨트롤을 검사하고 기대하는 컨트롤을 얻는 지 확인하십시오.
  • ...Sender나 EventArgs에 없나요?

업데이트 패널을 사용하지 마십시오....그들은 종종 가치 있는 것보다 더 많은 문제를 일으킬 수 있습니다.일반 AJAX를 사용하여 작업을 완료하는 것이 더 빠르고 덜 번거로울 수 있습니다.

UpdatePanel로 작업하는 경우 두 컨트롤이 모두 패널 내부에 있고 원하는 대로 작동하는지 확인하세요.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top