【问题标题】:Send json from ajax jquery to a controller that receive a model将 json 从 ajax jquery 发送到接收模型的控制器
【发布时间】:2014-09-25 15:07:56
【问题描述】:

我尝试了各种方式从 ajax 调用发送 json 并在 Action 中接收它,(我尝试过使用 webmethod 并遇到同样的问题),action 收到了一个具有 json 相同属性的模型。但收到 Action 的变量 person 始终为 null。

代码如下: 型号:

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
   }

行动:

   public ActionResult InsertPerson(Person person)
   {

        return View();

   }

最后是视图:

<input id="btnSend" type="button" value="Send" />

<script type="text/javascript">
$(document).ready(function () {
    var PersonDto = function (name, age) {
        this.Name = name;
        this.Age = age;
    };

    var person1 = new PersonDto("Diego", 27);


    $('#btnSend').on('click', function () {
        $.ajax({
            cache: false,
            url: '@Url.Action("InsertPerson", "JsonTest")',
            type: "GET",
            contentType: "application/x-www-form-urlencoded",
            dataType: "text",
            data: "{person:" + JSON.stringify(person1) + "}",

            success: function (data) {

                alert(data);

            },
            error: function (xhr, status, error) {
                alert(xhr);
                displayJsonError(xhr);
            }
        });

    });

});


</script>

我遵循的所有教程都显示了这种方式,我检查了数据中的 json,似乎没问题,我尝试在 web 方法中做同样的事情,但它没有用,不知道是什么我做错了。

【问题讨论】:

    标签: javascript jquery .net asp.net-mvc web-services


    【解决方案1】:

    您应该能够将数据简化并仅以 json 格式发布。请特别注意 type、contentType 和 data 属性。

        $.ajax({
            cache: false,
            url: '@Url.Action("InsertPerson", "JsonTest")',
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(person1),
            success: function (data) {
                alert(data);
            },
            error: function (xhr, status, error) {
                alert(xhr);
                displayJsonError(xhr);
            }
        });
    

    【讨论】:

    • 错误出现在 contentType 和类型中。数据以两种方式起作用。为什么它必须是 POST 类型?
    • 使用 POST 将数据放在请求正文中,而不是放在 url 参数中。一般来说,当你向服务器发送数据时,你应该使用 POST。
    猜你喜欢
    • 2011-08-09
    • 1970-01-01
    • 2021-09-07
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    相关资源
    最近更新 更多