c# - 从 JQuery 将 JSON 发布到 ASP.NET MVC 4 操作

标签 c# jquery json asp.net-mvc asp.net-mvc-4

我正在开发一个使用 ASP.NET MVC 4 的应用程序。在某些方面,我觉得我正在从头开始学习一切:)。有人告诉我这是值得的。

我需要将一些 JSON 发送到 Controller 中的操作。我的操作如下所示:

[Authorize]
public class MyController : Controller
{
    [HttpPost]
    public ActionResult RemoveItem(string itemID)
    {
      // Do stuff...
      return Json(new { Status = 1, Message="Success" });
    }
}

我的 JQuery 代码如下所示:

function removeItem(id) {
  var json = { "itemID": id };
  $.ajax({
    type: "POST",
    url: "/myController/removeItem",
    contentType: "application/json; charset=utf-8",
    data: json,
    dataType: "json",
    success: removeItemCompleted,
    error: removeItemFailed
  });
}

function removeItemCompleted(results) {
}

function removeItemFailed(request, status, error) {
}

在 Fiddler 中,我注意到返回了 500 错误。响应中的 TITLE 字段显示:“无效的 JSON 原语:itemID”。

我做错了什么?

谢谢!

最佳答案

请务必发送 JSON:

data: json,

应该是

data: JSON.stringify(json),

IE7 及以下版本需要垫片:https://github.com/douglascrockford/JSON-js

注意:Dave A 的回答也是正确的,但没有直接回答您的问题。我对其 +1。

关于c# - 从 JQuery 将 JSON 发布到 ASP.NET MVC 4 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14752522/

相关文章:

c# - 带有自定义响应包装器的 ASP.NET Core 3.1 Web API 中的 JSON 响应中断

c# - C# 中的字符串连接和标记化 xpath 函数

c# - 将本地文件与服务器文件同步

php - 从jquery mobile中的下拉列表中获取值并保存到mysql数据库

javascript - 如何对动态添加的列值求和?

json - 执行segue swift 4

c# - 使用 C# 合并新旧 XML 文件

c# - 流利的 C# 生成器

javascript - 如何显示Jquery结果

php - 使用不同类的 Android 发送 Json 对象