使用Jquery将空字典发布到ASP.NET MVC4操作

时间:2021-04-24 03:17:47

I'm using jquery to post dictionary to my controller action:

我正在使用jquery将字典发布到我的控制器操作:

Client-side code:

var dict = {};
// var dict = {"type": "type-1"}; // this works fine
$.post('/MyController/MyAction?id=' + jsId + '&data=' + jsData, { additionalFields : dict }, function () { //some callback });

Server-side code:

    public ActionResult MyAction([FromUri]Guid id, [FromUri]string data, [FromBody]Dictionary<string, string> additionalFields)
    {
        //some code
        return RedirectToAction("Index");
    }

If there are no additional data and dict variable is empty I receive strange data at the server side: additionalFields dictionary will contain two entries:

如果没有其他数据且dict变量为空,我会在服务器端收到奇怪的数据:additionalFields字典将包含两个条目:

controller: MyController

action: MyAction

How i can fix it?

我怎么解决它?

Here is picture that shows server-side data when i'm posting empty dictionary: 使用Jquery将空字典发布到ASP.NET MVC4操作

这是在我发布空字典时显示服务器端数据的图片:

2 个解决方案

#1


1  

try setting dict to null before posting to server when dictionary doesn't contain values

在字典不包含值时,尝试将dict设置为null,然后发布到服务器

dict = null;

#2


0  

It looks like the ModelBinder has picked some data in the body of the "Post" request. Why do you need [FromBody] attribute?

看起来ModelBinder已经在“Post”请求的主体中选择了一些数据。为什么需要[FromBody]属性?

Try remove it and that should resolve your issue.

尝试删除它,这应该可以解决您的问题。

#1


1  

try setting dict to null before posting to server when dictionary doesn't contain values

在字典不包含值时,尝试将dict设置为null,然后发布到服务器

dict = null;

#2


0  

It looks like the ModelBinder has picked some data in the body of the "Post" request. Why do you need [FromBody] attribute?

看起来ModelBinder已经在“Post”请求的主体中选择了一些数据。为什么需要[FromBody]属性?

Try remove it and that should resolve your issue.

尝试删除它,这应该可以解决您的问题。