如何在按钮按下事件期间获取我创建的信息以显示在我的html页面上?

时间:2012-08-29 17:40:51

标签: c# asp.net .net html

我正在使用visual studio 2010创建一个asp.net应用程序。我有一个文本字段和按钮,可以在文本字段中调用String上的方法。

Enter your address here: <asp:TextBox ID="tb_address" runat="server" ></asp:TextBox>
<asp:Button Text="Submit" runat="server" onclick="GetLatLong" ></asp:Button>

在按钮的C#文件中,我有GetLatLong方法:

protected void GetLatLong(object sender, EventArgs e)
{
    String address = tb_address.Text;
    String query = "http://maps.googleapis.com/maps/api/geocode/xml?address=";
    address = address.Replace(" ", "+");
    query += address + "&sensor=false";
    XmlDocument xDoc = new XmlDocument();
    xDoc.Load(query);
    String lat = xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat").InnerText;
    String lon = xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng").InnerText;
}

如何让我的lat和lon Strings显示在我的html页面上?

4 个答案:

答案 0 :(得分:3)

使用<asp:Label /> s。

<asp:Label ID="lblLat" runat="server" />
<asp:Label ID="lblLong" runat="server" />

String lat = xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat").InnerText;
String lon = xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng").InnerText;
lblLat.Text = lat;
lblLong.Text = lon;

答案 1 :(得分:3)

您必须创建用于显示结果的控件(您可以在设计模式下将它们添加到表单中,也可以在click事件处理程序中动态添加它们)。让我们说asp:标签,然后将结果值分配给那些标签。

Label result1 = new Label();
result1.Text = lat;
this.Controls.Add(result1);

在你的代码中有这个

<asp:Label ID='result1' runat='server' />

然后直接从后面的代码中分配值。

result1.Text = lat;

答案 2 :(得分:2)

您可以包含一些Literal控件(或Label控件或任意数量的其他页面元素)来保存值。控件看起来像这样:

<asp:Literal runat="server" ID="LatitudeOutput" />
<asp:Literal runat="server" ID="LongitudeOutput" />

你要在代码隐藏中设置它们的值:

String lat = xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat").InnerText;
String lon = xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng").InnerText;
LatitudeOutput.Text = lat;
LatitudeOutput.Text = lon;

在很多情况下,我个人更喜欢Literal控件,因为它们不会带来任何额外的标记。例如,Label控件包含在span标记中。但是,与许多事情一样,有很多方法可以做到。

答案 3 :(得分:1)

您必须在aspx页面上创建标签控件。将其添加到要在其中显示lng和lat

的aspx页面
<asp:Label ID="lblLat" runat="server" />
<asp:Label ID="lblLng" runat="server" />

然后在你的代码中

lblLat.Text = xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat").InnerText;
lblLng.Text = xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng").InnerText;

您正在将标签的文本设置为您使用SelectSingleNode调用获得的值。