c# - mvc3 Controller 方法中的ajax发布数据为空

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

我的一个 jquery ajax 帖子将帖子数据发送到我的 .NET MVC3 Controller 方法,但在 Controller 方法中,数据显示为空。我还有许多其他使用几乎相同方法主体的 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
    }
});

Controller 方法:

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

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

关于为什么帖子看起来不错,但 Controller 没有获取数据有什么建议或想法吗?

最佳答案

but at the controller method, the data shows up as null

这是不可能的,因为 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 请求定义一个 View 模型:

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

然后让你的 Controller 将这个 View 模型作为参数:

[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
    }
});

关于c# - mvc3 Controller 方法中的ajax发布数据为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14013024/

相关文章:

c# - 为什么 MenuItem 标题前面有下划线?

c# - 防止 Visual Studio 调试在明显的 "unhandled exception"上中断

jQuery ajax 图片上传

javascript - js - 固定缓冲区到屏幕底部的长表单/div,以便用户可以看到前方

c# - 堆栈中的对象创建

c# - Scaffold-DbContext 在.net core 中抛出错误 "Could not find assembly"

c# - CLR 级别的转换实际上是如何工作的?

c# - 为什么我可以在 C# 中像数组一样初始化一个列表?

javascript - jQuery datetimepicker 在给定开始时设置结束日期

c# - 未知服务器标记 'rsweb:ReportViewer'