Skip to main content
 首页 » 编程设计

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

2024年02月20日33birdshome

我的一个 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 
    } 
});