Sending a javascript array to code behind(c#) using ajax(使用 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.
我的问题是
我可以使用这种方法传递数组吗?
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 控制器
HTML 和 jQuery 看起来几乎完全相同,除了您调用 WebMethod 的位置.
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#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!