我对 C# 和 javascript 有点陌生,所以虽然我的问题很具体,但我愿意接受任何替代方案。
我有一组值(我在 javascript 函数中创建的),我想发送到我的代码隐藏文件以在方法中使用。根据我的研究,使用 ajax 并使用 JSON 对数组进行字符串化似乎是最好的方法。
我的问题是
我可以使用这种方法传递数组吗?
如何在服务器端捕获信息(在我的代码隐藏中?)
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/