【发布时间】:2014-12-28 03:03:45
【问题描述】:
我在将我的 Javascript 对象数组发布到 C# Codebehind 时遇到一些问题。我遵循了一个简单的教程,并认为这会很好地工作,但我在 PassThings 中的 C# 代码隐藏断点从未被命中。
我已尝试将 url 更改为“Default.aspx/PassThings”,但它仍然从未发布到我的代码后面,错误警报显示“[object object”]
这是我的客户端:
Default.aspx
脚本
<script>
function Save() {
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/PassThings',
data: things,
success: function () {
alert("success");
},
error: function (response) {
alert(response);
}
});
});
}
</script>
HTML
<input type="button" value="Pass Things" onclick="JavaScript: Save();">
Default.aspx.cs
代码隐藏
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Services;
[System.Web.Script.Services.ScriptService]
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public void PassThings(List<Thing> things)
{
var t = things;
}
public class Thing
{
public int Id { get; set; }
public string Color { get; set; }
}
}
有人看到我做错了吗?
感谢您的宝贵时间。
【问题讨论】:
-
需要定义
PassThings函数web方法 -
@Satpal 我在 c# 代码隐藏中的 PassThings 上方添加了 [WebMethod],但仍然没有命中回发断点,我还添加了 [System.Web.Script.Services.ScriptService]
-
尝试在ajax调用中添加
traditional : true属性 -
@EhsanSajjad 没有效果:(
-
失败回调可能应该是“错误”。 api.jquery.com/jquery.ajax
标签: javascript c# asp.net ajax json