c# - 使用 ajax 将 javascript 数组发送到代码隐藏 (c#)

标签 c# javascript jquery asp.net 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
});

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

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

[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
}

最佳答案

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

Send data with jquery to an MVC controller

HTML 和 jQuery 看起来几乎完全一样,除了调用 WebMethod 的地方。

如果您使用的页面名为 Default.aspx,方法名为 Done,则 WebMethod 的 URL 将为 Default.aspx/完成

<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>

您的 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.
}

关于c# - 使用 ajax 将 javascript 数组发送到代码隐藏 (c#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11123545/

相关文章:

c# - 如何替换字符串中特定出现的字符串?

javascript - 无法使用javascript访问json对象

javascript - 为什么 Angular 在使用不同的字符串时表现出意外?

java - 这两种方法一起是一种递归形式吗?

c# - 我可以在 Xamarin 上使用 WPF 的全屏 UI 吗?

c# - 如何将一个简单的类解析为 Bson 和 MongoDB 集合

javascript - 加载时自动登录网站 - 用户脚本(JS)

javascript - 如何为 jquery 调用 `$(some)` 创建 spy ?

javascript - JQuery Replacewith DIV 未加载

jquery - 编辑 CSS 以消除列末尾的边距