使用ajax将javascript数组发送到后面的代码(c#)

Mat*_*can 9 javascript c# asp.net jquery webforms

我对C#和javascript有点新意,所以虽然我的问题是具体的,但我对任何替代方案持开放态度.

我有一个值数组(我在javascript函数中创建),我想发送到我的代码隐藏文件,以便在方法中使用.从我使用ajax研究并使用JSON对数组进行字符串化似乎是最好的方法.

我的问题是

  1. 我可以使用这种方法传递数组吗?

  2. 如何捕获服务器端的信息(在我的代码隐藏中?)

Javascript传递值

var jsonvalues = JSON.stringify(values);
var callback = window.location.href
$.ajax({
  url: callback
  type: "POST",
  contentType: 'application/json',
  data: jsonvalues
});
Run Code Online (Sandbox Code Playgroud)

我已经看到很多使用[WebMethod]或某种WebService来捕获数据的解决方案,我可以使用它在我的代码隐藏文件中工作而不必返回数据吗?

这是我在代码隐藏文件中使用的内容

[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ast 6

我使用ASP.NET MVC为此编写了一个深入的示例,但它可以很容易地适用于WebForms.

使用jquery将数据发送到MVC控制器

HTML和jQuery看起来几乎完全相同,除了你调用WebMethod的地方.

如果调用了您正在使用的页面Default.aspx,并且调用了该方法Done,那么您将使用WebMethod的URL Default.aspx/Done.

<script>
       // Grab the information 
       var values = {"1,","2","3"};
       var theIds = JSON.stringify(values);

       // Make the ajax call
       $.ajax({
         type: "POST",
         url: "Default.aspx/Done", // the method we are calling
         contentType: "application/json; charset=utf-8",
         data: {ids: theIds },
         dataType: "json",
         success: function (result) {
             alert('Yay! It worked!');               
         },
         error: function (result) {
             alert('Oh no :(');
         }
     });
  </script>
Run Code Online (Sandbox Code Playgroud)

你的WebMethod意志仍然是一样的.

[WebMethod]
public static void done(string[] ids)
{
   String[] a = ids;
   // Do whatever processing you want
   // However, you cannot access server controls
   // in a static web method.
}
Run Code Online (Sandbox Code Playgroud)