javascript - 如何将 Javascript 字典传递给 Controller ​​,其中 C# 字典值是一个对象

标签 javascript c# jquery asp.net-mvc asp.net-core

想象一下这个 Javascript 字典:

var things = {};
things['1'] = 10;
things['2'] = 11;

这里有一些 ajax 代码:

$.ajax({
    url: '/Controller/Foo',
    type: 'POST',
    data: {
        things: things
    },

这是有效的:

[HttpPost]
public IActionResult Foo(Dictionary<string, int> things)

things 将显示 1 映射到 10,2 映射到 11。

这是不起作用的:

[HttpPost]
public IActionResult Foo(Dictionary<string, object> things)

things 将显示 1 映射到 null,2 映射到 null。

我无法更改词典类型。实际上,该 Dictionary 是整个应用程序(在 C# 方面)使用的复杂对象的一部分。您所看到的是一个简单的示例。

此外,JSON.stringify 根本没有帮助。事实上,如果我对字典进行字符串化,我得到的计数为 0,没有任何值。

使用 C# 来表达我的观点,我认为期望更多的是这样的(比当前正在发生的情况):

int x = 5;
object foo = (object)x;

字典是这样定义的,因为人们可以这样做:

things[key] = 1;

things[key] = "string";

这就是它被声明为对象的原因。

如果重要的话,我正在使用 ASP.NET Core(以及 jquery 3.4.1)。

谢谢。

最佳答案

您可以自定义一个DictionaryModelBinder,如下所示:

 public class DictionaryModelBinder:IModelBinder
{
    public  Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
            throw new ArgumentNullException(nameof(bindingContext));

        var result = new Dictionary<string, object> {};
        var form = bindingContext.HttpContext.Request.Form;
        if (form==null)
        {
            bindingContext.ModelState.AddModelError("FormData", "The data is null");
            return Task.CompletedTask;
        }
        foreach ( var k in form.Keys){
            StringValues v = string.Empty;
            var flag = form.TryGetValue(k, out v);
            if (flag)
            { 
                result.Add(k, v );
            }
        }

        bindingContext.Result = ModelBindingResult.Success(result);
        return Task.CompletedTask;
    }
}

Controller :

[HttpPost]
    public IActionResult Foo([ModelBinder(BinderType = typeof(DictionaryModelBinder))]Dictionary<string, object> things)
    {
        // the stuff you want
    }

关于javascript - 如何将 Javascript 字典传递给 Controller ​​,其中 C# 字典值是一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57499215/

相关文章:

c# - 将 EF6 数据库优先从 SQL Server 迁移到 PostgreSQL

jquery - 从 jquery 中的 DOM 访问大子元素?

javascript - 如何使用 jquery 查找图像名称?

jquery - 点击后弹出全屏div

javascript - Web Worker 与 Promise

javascript - 使用具有透明 PNG 的 Canvas 进行像素化调整大小

c# - 在重载方法上使用泛型参数

c# - 将数量封装在结构中以实现类型安全会对性能产生影响吗?

javascript - ng-disabled 不使用 <i> 标签使用 font-awesome

javascript - 使用 Javascript 根据键值转换 JSON