简体   繁体   中英

Textbox Autopostback not triggering

Please have a look at my code below written in ASP.NET. I have Google Places Search API on my page. I have a txtSearch textbox control that is linked with the Google API. When you start search it shows a list of suggestions provided by Google Places from which you can select one. I have a function FindCoordinates that gets the location from txtSearch and passes it to Google Maps API and gets the coordinates which are then used to populate the listview control. The problem here is that txtSearch won't trigger AutoPostback or textChanged functions. I've tried many solutions, onBlur, onKeyup, tried calling a static function from JavaScript but nothing seems to work.

Front page:

<%@ Page Title="Search Reviews" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="SearchReviews.aspx.cs" Inherits="Content_SearchReviews" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %> 

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script type="text/javascript">
    function LoadGoogleMAP() {

        var markers = [];
        var map = new google.maps.Map(document.getElementById('map_canvas'), {
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var lat = document.getElementById('<%=txtLatitude.ClientID%>').value;
        var lon = document.getElementById('<%=txtLongitude.ClientID%>').value;
        var myLatlng = new google.maps.LatLng(lat, lon)

        var defaultBounds = new google.maps.LatLngBounds(myLatlng, myLatlng);
          //new google.maps.LatLng(-33.8902, 151.1759),
          //new google.maps.LatLng(-33.8474, 151.2631));
        map.fitBounds(defaultBounds);

        // Create the search box and link it to the UI element.  
        var input = (document.getElementById('MainContent_txtSearch'));
        map.controls[google.maps.ControlPosition.CENTER].push(input);

        var searchBox = new google.maps.places.SearchBox((input));

        // Listen for the event fired when the user selects an item from the  
        // pick list. Retrieve the matching places for that item.  
        google.maps.event.addListener(searchBox, 'places_changed', function () {
            //PageMethods.UpdateResults("Hello");

            var places = searchBox.getPlaces();

            if (places.length == 0) {
                return;
            }
            for (var i = 0, marker; marker = markers[i]; i++) {
                marker.setMap(null);
            }

            // For each place, get the icon, place name, and location.  
            markers = [];
            var bounds = new google.maps.LatLngBounds();
            for (var i = 0, place; place = places[i]; i++) {
                var image = {
                    url: place.icon,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(25, 25)
                };

                // Create a marker for each place.  
                var marker = new google.maps.Marker({
                    map: map,
                    icon: image,
                    title: place.name,
                    position: place.geometry.location
                });

                markers.push(marker);

                bounds.extend(place.geometry.location);
            }

            map.fitBounds(bounds);
        });


        // current map's viewport.  
        google.maps.event.addListener(map, 'bounds_changed', function () {
            var bounds = map.getBounds();
            searchBox.setBounds(bounds);
        });
    }

    //google.maps.event.addDomListener(window, 'load', LoadGoogleMAP);

</script>
<script type="text/javascript">
    function RefreshUpdatePanel() {
        __doPostBack('<%= txtSearch.ClientID %>', '');
    };
</script>

<div class="row setPadding" style="background:#333333; color:#ffffff;">
    <asp:Label ID="lblHeading" runat="server" Text="Search Reviews" Font-Bold="True" Font-Size="Large"></asp:Label><br />
</div>

<div class="row">
    <div id="map_canvas"></div>
</div>
<div class="row setPadding">
    <div class="col-lg-10 col-lg-offset-1 col-md-10 col-md-offset-1 col-sm-10 col-sm-offset-1 col-xs-12 col-xs-offset-1">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <asp:TextBox ID="txtSearch" CssClass="form-control" runat="server" placeholder="search address" AutoPostBack="true" OnTextChanged="txtSearch_TextChanged" EventName="TextChanged"></asp:TextBox>
        </div>

        <div class="hideContent">
            <div class="col-lg-6 col-md-12 col-sm-12 col-xs-12">
                <div class="form-group">
                    <asp:Label runat="server" AssociatedControlID="txtLatitude" CssClass="col-lg-6 col-md-3 col-sm-4 control-label">Latitude</asp:Label>
                    <div class="col-lg-6 col-md-5 col-sm-8">
                        <asp:TextBox runat="server" ID="txtLatitude" CssClass="form-control" Enabled="False" />
                    </div>
                </div>
            </div>

            <div class="col-lg-6 col-md-12 col-sm-12 col-xs-12">
                <div class="form-group">
                    <asp:Label runat="server" AssociatedControlID="txtLongitude" CssClass="col-lg-6 col-md-3 col-sm-4 control-label">Longitude</asp:Label>
                    <div class="col-lg-6 col-md-5 col-sm-8">
                        <asp:TextBox runat="server" ID="txtLongitude" CssClass="form-control" Enabled="False" />
                    </div>
                </div>
            </div>
        </div>

        <%--<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">--%>
            <asp:ListView ID="lstSearchReviews" runat="server" DataSourceID="dsSearchReviews">
                <ItemTemplate>
                    <div class="row ratingBackground">
                        <div class="col-lg-2 col-md-2 col-sm-2 col-xs-12">
                            <asp:Image ID="imgPhoto" ImageUrl='<%# GetImage(Eval("imgImage")) %>' CssClass="img-responsive center-block img-rounded" runat="server" /> 
                        </div>                            
                        <div class="col-lg-7 col-md-7 col-sm-7 col-xs-12">
                            <a href="ViewProperty.aspx?nPropertyId=<%# Eval("nPropertyId") %>"><asp:Label ID="Label1" runat="server" CssClass="ratingHeading" Text='<%# Eval("vcAddressLine1") %>' /> <asp:Label ID="Label2" runat="server" CssClass="ratingHeading" Text='<%# Eval("vcAddressLine2") %>' /></a>
                            <br>
                            <asp:Label ID="Label3" runat="server" Text='<%# Eval("vcCity") %>' /> <asp:Label ID="Label4" runat="server" CssClass="ratingHeading" Text='<%# Eval("vcPostCode") %>' />
                            <br />
                            <asp:Label ID="Label5" runat="server" Text='<%# Eval("vcCountry") %>' />
                            <br />
                            <asp:Label ID="Label6" runat="server" Text='<%# Eval("PropertyType") %>' />
                        </div>                            
                        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
                            <cc1:Rating ID="rating1" AutoPostBack="false"
                                StarCssClass="Star" WaitingStarCssClass="WaitingStar" EmptyStarCssClass="Star"
                                FilledStarCssClass="FilledStar" CurrentRating='<%# Eval("AverageRating") %>' runat="server" ReadOnly="true" ViewStateMode="Disabled">
                            </cc1:Rating>
                            <br />
                            <asp:Label ID="Label7" runat="server" CssClass="ratingHeading" Text='<%# Eval("TotalReviews") %>' /> <span class="ratingHeading"> Review(s)</span>
                        </div>                            
                    </div>
                </ItemTemplate>
                <LayoutTemplate>
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <div id="itemPlaceholderContainer" runat="server" style="font-family: Verdana, Arial, Helvetica, sans-serif;">
                            <span runat="server" id="itemPlaceholder" />
                        </div>
                    </div>
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                            <asp:DataPager ID="DataPager1" runat="server">
                                <Fields>
                                    <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True" />
                                </Fields>
                            </asp:DataPager>
                    </div>
                </LayoutTemplate>
                <EmptyDataTemplate>
                    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                        <p class="text-danger" style="margin:10px 0;"><span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true""></span><strong> No results found. Please try a different search. </strong></p>
                    </div>
                </EmptyDataTemplate>
            </asp:ListView>
            <asp:SqlDataSource ID="dsSearchReviews" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand=""></asp:SqlDataSource>

    </div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>

Code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;

public partial class Content_SearchReviews : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        Session["CurrentPage"] = "SearchReviews.aspx";

        if (!IsPostBack)
        {
            if (Session["FormattedAddress"] != null)
            {
                txtSearch.Text = Convert.ToString(Session["FormattedAddress"]);
            }
        }

        FindCoordinates(null, null);
        setDataSource();
    }

    protected void FindCoordinates(object sender, EventArgs e)
    {
        string sLocation = "";

        if (txtSearch.Text == "")
        {
            sLocation = "London, United Kingdom";
        }
        else
        {
            sLocation = txtSearch.Text;
        }
        string url = "http://maps.google.com/maps/api/geocode/xml?address=" + sLocation + "&partial_match=false&location_type=ROOFTOP&street_address=" + sLocation + "&sensor=false";
        WebRequest request = WebRequest.Create(url);

        using (WebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                DataSet dsResult = new DataSet();
                dsResult.ReadXml(reader);
                DataTable dtCoordinates = new DataTable();
                dtCoordinates.Columns.AddRange(new DataColumn[4] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Address", typeof(string)),
                        new DataColumn("Latitude",typeof(string)),
                        new DataColumn("Longitude",typeof(string)) });

                foreach (DataRow row in dsResult.Tables["result"].Rows)
                {
                    string geometry_id = dsResult.Tables["geometry"].Select("result_id = " + row["result_id"].ToString())[0]["geometry_id"].ToString();
                    DataRow location = dsResult.Tables["location"].Select("geometry_id = " + geometry_id)[0];
                    dtCoordinates.Rows.Add(row["result_id"], row["formatted_address"], location["lat"], location["lng"]);
                    txtLatitude.Text = Convert.ToString(location["lat"]);
                    txtLongitude.Text = Convert.ToString(location["lng"]);
                    ScriptManager.RegisterStartupScript(this, GetType(), "LoadGoogleMAP", "LoadGoogleMAP();", true);
                }
            }
        }
    }

    protected void setDataSource()
    {
        dsSearchReviews.SelectCommand = "Select a.nPropertyId, a.vcCompleteAddress, a.vcAddressLine1, a.vcAddressLine2, a.vcCity, a.vcPostCode, a.vcCountry, CASE nPropertyTypeId WHEN 1 Then 'Flat' WHEN 2 THEN 'House' When 3 THEN 'House (Semi-Detatched)' WHEN 4 THEN 'HOUSE (Detatched)' END Propertytype, (Select cast(avg(flRatingOverall) as int) flRatingOverall From dbo.Reviews Where nPropertyId = a.nPropertyId) AverageRating, (Select COUNT(nReviewId) TotalRatings From dbo.Reviews Where nPropertyId = a.nPropertyId) TotalReviews, SQRT(POWER(dLatitude - " + Convert.ToDouble(txtLatitude.Text) + ", 2) + POWER(dLongitude - " + Convert.ToDouble(txtLongitude.Text) + ", 2)) * 62.1371192 AS DistanceFromAddress, imgImage From Properties a WHERE ABS(dLatitude - " + Convert.ToDouble(txtLatitude.Text) + ") < 0.50 AND ABS(dLongitude - " + Convert.ToDouble(txtLongitude.Text) + ") < 0.50";
        dsSearchReviews.DataBind();
        lstSearchReviews.DataBind();
    }

    public string GetImage(object img)
    {
        return "data:image/png;base64," + Convert.ToBase64String((byte[])img);
    }

    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        FindCoordinates(null, null);
        setDataSource();
    }

    //[System.Web.Services.WebMethod]
    //public static string UpdateResults(string greeting)
    //{
    //    Content_SearchReviews updatePage = new Content_SearchReviews();
    //    updatePage.Session["FormattedAddress"] = updatePage.txtSearch.Text;
    //    updatePage.FindCoordinates(null, null);
    //    updatePage.setDataSource();
    //    return greeting;
    //}

}

After a lot of debugging I figured out that the setDataSource() function was preventing the autopostback. I set the property of listview EnableViewState="false" and that did the trick. It works fine now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM