[英]Pass C# Data Result to JavaScript Variable
我需要将下面的 SQL 结果传递给 ASP.Net 中的 Javascript? 我试图在 JS 中声明这两个字段,但不能正确。 我如何在 JS 中获得结果?
var Description = "<%=this.Description%>"
var ApplicationSourceCount = "<%=this.ApplicationSourceCount%>"
在 C# 中声明字符串
public class ApplicantSourceData
{
public string Description { get; set; }
public string ApplicantSourceCount { get; set; }
}
C# 网络方法
[WebMethod]
public List<ApplicantSourceData> GetApplicantSourceData(List<string> aData)
{
//SqlDataReader reader;
List<ApplicantSourceData> GetApplicantSourceData = new List<ApplicantSourceData>();
string connectionString = ConfigurationManager.ConnectionStrings["ATL2"].ConnectionString;
string commandTextApplicantsByMonthCount = Properties.Queries.commandTextApplicantsByMonthCount;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(commandTextApplicantsByMonthCount))
{
command.CommandText = commandTextApplicantsByMonthCount;
command.CommandType = CommandType.Text;
command.Connection = con;
con.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
int counter = 0;
while (reader.Read())
{
ApplicantSourceData tsData = new ApplicantSourceData();
tsData.Description = reader["Description"].ToString();
tsData.ApplicantSourceCount = reader["ApplicantSourceCount"].ToString();
GetApplicantSourceData.Add(tsData);
counter++;
}
}
}
return GetApplicantSourceData;
}
}
我尝试了以下方法,但没有
您应该从客户端调用您的 WebMethod(例如,作为 AJAX 请求)。 然后,您应该让 WebMethod 使用请求的数据(例如,作为 JSON 格式的字符串)向客户端返回响应。
有几种方法可以做到这一点。 第一种是使用 AJAX。
例子:
C#:
[WebMethod]
public static string someWebMethod(String data) {
// your code here
var returnData = /* some kind of data */
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(returnData);
}
JS(以 jQuery 为例,但您也可以在常规 JS 中执行此操作):
$.ajax({
type: "POST",
url: "PageName.aspx/someWebMethod",
data: "{"data": data}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
// Do something with the response.
}
});
另一种选择是使用PageMethods
。 为此,您可以按照如下模式从 JS 中调用该方法:
PageMethods.someWebMethod(data);
function onSucess(result) {
console.log(result);
}
function onError(result) {
console.log(result);
}
我建议也多看看 ASP.NET WebMethod 文档。 此外,这里有一些可能有帮助的教程: 使用 jQuery-AJAX 调用 ASP.NET WebMethod和使用 JavaScript 调用 ASP.NET C# 方法(Web 方法) 。
你的解决方案似乎不起作用,你在 github 或其他东西上有完整的解决方案吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.