【问题标题】:ajax post data null in mvc3 controller methodmvc3控制器方法中的ajax发布数据为空
【发布时间】:2012-12-23 17:26:25
【问题描述】:

我的一个 jquery ajax 帖子将帖子数据发送到我的 .NET MVC3 控制器方法,但在控制器方法中,数据显示为空。我有许多其他 ajax 帖子使用几乎相同的方法体,而且它们都工作正常,所以我不确定发生了什么。

Ajax 帖子:

$.ajax({
    url: '/Entity/Relate',
    type: 'POST',
    dataType: 'json',
    contentType: 'applicaiton/json; charset=utf-8',
    data: { primaryEntityId: parseInt(entityParentId, 10), relatedEntityId: _createdId },
    success: function (data)
    {
        //do stuff
    },
    error: function ()
    {
        // throw error
    },
    complete: function ()
    {
        //do more stuff
    }
});

控制器方法:

[HttpPost]
public int Relate(int primaryEntityId, int relatedEntityId)
{
    return relationshipRepository.Add(primaryEntityId, relatedEntityId);
}

问题是当我中断 Relate 方法时,primaryEntityId 和 relatedEntityId 为空,即使在 Firebug 中的发布数据中,它显示 {primaryEntityId: 13, relatedEntityId: 486} 已发布到该方法。

关于为什么帖子看起来不错,但控制器没有获取数据的任何建议或想法?

【问题讨论】:

    标签: c# jquery .net ajax asp.net-mvc-3


    【解决方案1】:

    但在控制器方法中,数据显示为空

    这是不可能的,因为 Int32 是一个值类型,而 .NET 中的值类型不能是 null。您可能意味着将它们分配给默认值。无论如何。

    问题与您在 AJAX 请求中设置的 contentType 参数有关。您需要删除它,因为您发送的不是 JSON,而是标准的 application/x-www-form-urlencoded 请求:

    $.ajax({
        url: '/Entity/Relate',
        type: 'POST',
        dataType: 'json',
        data: { 
            primaryEntityId: parseInt(entityParentId, 10), 
            relatedEntityId: _createdId 
        },
        success: function (data)
        {
            //do stuff
        },
        error: function ()
        {
            // throw error
        },
        complete: function ()
        {
            //do more stuff
        }
    });
    

    如果要发送 JSON 请求,请定义视图模型:

    public class RelateViewModel
    {
        public int PrimaryEntityId { get; set; }
        public int RelatedEntityId { get; set; }
    }
    

    然后让您的控制器将此视图模型作为参数:

    [HttpPost]
    public int Relate(RelateViewModel model)
    {
        return relationshipRepository.Add(model.PrimaryEntityId, model.RelatedEntityId);
    }
    

    最后发送一个真正的 JSON 请求(使用JSON.stringify 方法):

    $.ajax({
        url: '/Entity/Relate',
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify({ 
            primaryEntityId: parseInt(entityParentId, 10), 
            relatedEntityId: _createdId 
        }),
        success: function (data)
        {
            //do stuff
        },
        error: function ()
        {
            // throw error
        },
        complete: function ()
        {
            //do more stuff
        }
    });
    

    【讨论】:

    • 感谢您纠正我的错误。问题是服务器的响应说 INT32 的值不能为空。事实证明,有一个非常小的错字导致了整个问题,即我在 contentType 语句中拼错了“应用程序”……那个,在我的示例中,我没有使用 JSON.stringify。感谢您提供信息,这很有帮助。
    猜你喜欢
    • 2014-01-22
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 2016-05-28
    相关资源
    最近更新 更多