c# - 如何将 JSON 文件发布到 ASP.NET MVC 操作?

标签 c# asp.net asp.net-mvc

我的 iphone 客户端将以下 json 发布到我的 mvc 服务。 从 html 表单发布数据时,它会自动将表单数据转换为 UserModel 并将对象传递给我的 Create 方法,但是当我从 iphone 发送请求正文中的 JSON 字符串时,它返回为 null。

从 JSON 到 Object 的转换最干净的解决方案是什么。

我不想为不同的客户端创建多个方法,所以我试图让相同的方法在 iphone 和 mvc 客户端上工作。

我的请求正文:

{
   "firstName" : "Some Name",
   "lastName" : "Some Last Name",
   "age" : "age"
}

我的模型和行动结果

public class UserModel
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public int Age { get; set; }
}

[HttpPost]
public Create ActionResult(UserModel user)
{
   // user is null
   userStorage.create(user);
   return SuccessResultForModel(user);
}

最佳答案

您需要将 HTTP header accept 设置为“application/json”,以便 MVC 知道您正在传递 JSON 并执行解释它的工作。

accept: application/json

在此处查看更多信息:http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

更新:使用 MVC3 和 jQuery 的工作示例代码

Controller 代码

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult PostUser(UserModel data)
        {
            // test here!
            Debug.Assert(data != null);
            return Json(data);
        }
    }

    public class UserModel
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
}

查看代码

@{ ViewBag.Title = "Index"; }
<script src="../../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    var sample = {};
    sample.postData = function () {
        $.ajax({
            type: "POST", url: "@Url.Action("PostUser")",
            success: function (data) { alert('data: ' + data); },
            data: JSON.stringify({ "firstName": "Some Name", "lastName": "Some Last Name", "age": "30" }),
            accept: 'application/json'
        });
    };
    $(document).ready(function () {
        sample.postData();
    });
</script>

<h2>Index</h2>

** 更新 ** 在将它传递给 AJAX 请求中的 data 元素之前,我将 JSON.stringify 添加到 JS 对象。这只会使有效载荷更具可读性,但是 Controller 将以类似的方式解释 data 的两种格式。

关于c# - 如何将 JSON 文件发布到 ASP.NET MVC 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15317856/

相关文章:

c# - 如何在 ASP.NET Core 中使用 SqlClient?

c# - ASP.NET : Get Label inside Repeater using JQuery based on custom attribute

c# - 将 C# 集合拆分为相等的部分,保持排序

c# - 使用 ASP.NET MVC 中父页面模型的内容填充 PartialView 模型

c# - 可选周围标签的优雅 MVC 代码

.net - Umbraco 学习资源?

c# - 使用 C# 重建更新的 VB6 COM 类替换

c# - 任务并行库 - 如何立即返回但有一个并行步骤

c# - 强制 C# 方法只传递正参数?

c# - 如何在 OfType() 之后使用 Include()?