将C#数据结果传递给JavaScript变量

时间:2018-06-05 09:48:55

标签: javascript c# asp.net webmethod

我需要将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

[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;
        }
    }

我已经尝试了以下内容,但它没有

1 个答案:

答案 0 :(得分:1)

您应该从客户端调用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文档。此外,这里有一些可能有用的教程:Calling ASP.NET WebMethod using jQuery-AJAXCalling an ASP.NET C# Method (Web Method) Using JavaScript