[英]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.