我在asp.net中有PageMethods的问题,我有一个调用JavaScript函数的按钮,这个函数有一个PageMethod,它从我的c#codebehind中的方法返回一个值。 但是当我点击按钮时,PageMethod不返回任何内容,返回值直到我第二次单击该按钮。
<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
这是我的asp.net代码:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
<asp:Button ID="btnViaje" runat="server" Text="Viajes" OnClientClick="CargarViajes(); return false;" />
<asp:Button ID="btnRuta" runat="server" Text="Ruta" OnClientClick="CargarRuta(); return false;" />
<div id="map_canvas" style="width:900px;display:block;float:left"></div>
<p id="co" style="display:block; float:left">Estadia: </p>
<input type="hidden" value="" id="SendA" name="SendA" />
<button onclick="rastreo()" style="width:50px;height:20px;">rastreo</button>
</form>
当我点击按钮btnViaje调用javascript函数但响应没有返回任何内容,直到我再次点击按钮:
function CargarViajes() {
PageMethods.ConvertDataTabletoString(function (response) {
camiones = eval("(function(){return " + response + ";})()"
);
});
}
这是我的c#方法:
[WebMethod]
public static string ConvertDataTabletoString()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=PROYECTOLALAE2\\SQLEXPRESS;Initial Catalog=DB_LALA_Rastreo_Rastreo;Integrated Security=true"))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id_Viaje=idviaje, LatV=latitud, LonV=longitud, Velocidad=velocidad, In1=entrada1_dig, In2=entrada2_dig, AI1=entrada1_analoga, AI2=entrada2_analoga FROM Tb_Viaje_Coordenada", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
}
}
答案 0 :(得分:0)
像这样更新您的JavaScript:
function CargarViajes() {
PageMethods.ConvertDataTabletoString(OnSucceeded);
}
function OnSucceeded(result, userContext, methodName)
{
if (methodName == "ConvertDataTabletoString")
{
// Now do whatever you like with results from ConvertDataTabletoString
return result;
}
}