使用Ajax将JavaScript数组发送到代码背后(C#) [英] Sending a javascript array to code behind(c#) using ajax

查看:56
本文介绍了使用Ajax将JavaScript数组发送到代码背后(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C#和javascript有点陌生,所以虽然我的问题很具体,但是我可以接受其他选择.

I'm a bit new to C# and javascript so while my question is specific I am open to any alternatives.

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

I have an array of values (that I have created in a javascript function) that I want to send to my code-behind file to be used in a method. From what I've researched using ajax and stringifying the array with JSON seems like the best method.

我的问题是

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

  1. Can I pass the array using this method?

如何捕获服务器端的信息(在我的后台代码中?)

How do I capture the information on the server side(in my code-behind?)

传递值的Javascript

Javascript passing the values

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

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

I've seen many solutions using [WebMethod] or some kind of WebService to capture the data, can I use this to do work in my code-behind file without having to return data?

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

Here is what I'm using on my code-behind file

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

推荐答案

我已经使用ASP.NET MVC编写了一个深入的示例,但是可以轻松地将其应用于WebForms.

I have written a in-depth example for this using ASP.NET MVC, but it can easily be adapted for WebForms.

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

除了调用WebMethod的位置外,HTML和jQuery看起来几乎完全相同.

The HTML and jQuery will look almost exactly the same, with the exception of where you call the WebMethod.

如果您正在使用的页面被称为 Default.aspx ,而该方法被称为 Done ,则WebMethod的URL将为 Default.aspx/完成.

If the page you are using is called Default.aspx, and the method is called Done, then your URL for the WebMethod will be 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>

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

这篇关于使用Ajax将JavaScript数组发送到代码背后(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆