jQuery 将动态 json 对象传递给 C# MVC 控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5022958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:24:27  来源:igfitidea点击:

Passing dynamic json object to C# MVC controller

jqueryjsonasp.net-mvc-3

提问by Gareth Hastings

I am doing some work with .Net 4, MVC 3 and jQuery v1.5

我正在使用 .Net 4、MVC 3 和 jQuery v1.5

I have a JSON object that can change depending on which page is calling it. I'd like to pass the object to a controller.

我有一个 JSON 对象,可以根据调用它的页面进行更改。我想将对象传递给控制器​​。

{ id: 1, title: "Some text", category: "test" }

I understand that if I create a custom model such as

我知道如果我创建一个自定义模型,例如

[Serializable]
public class myObject
{
    public int id { get; set; }
    public string title { get; set; }
    public string category { get; set; }
}

and use this in my controller such as

并在我的控制器中使用它,例如

public void DoSomething(myObject data)
{
    // do something
}

and pass the object using jQuery's .ajax method like this:

并使用 jQuery 的 .ajax 方法传递对象,如下所示:

$.ajax({ 
    type: "POST", 
    url: "/controller/method", 
    myjsonobject,  
    dataType: "json", 
    traditional: true
});

This works fine, my JSON object is mapped to my C# object. What I'd like to do is pass through a JSON object that's likely to change. When it changes I don't want to have to add items to my C# model each time the JSON object changes.

这工作正常,我的 JSON 对象映射到我的 C# 对象。我想做的是传递一个可能会改变的 JSON 对象。当它更改时,我不想在每次 JSON 对象更改时都向我的 C# 模型添加项目。

Is this actually possible? I tried mapping objects to a Dictionary but the value of data would just end up being null.

这真的可能吗?我尝试将对象映射到字典,但数据的值最终会为空。

Thanks

谢谢

回答by Buildstarted

Presumably the action that accepts input is only used for this particular purpose so you could just use the FormCollectionobject and then all your json properties of your object will be added to the string collection.

据推测,接受输入的操作仅用于此特定目的,因此您可以只使用FormCollection对象,然后对象的所有 json 属性都将添加到字符串集合中。

[HttpPost]
public JsonResult JsonAction(FormCollection collection)
{
    string id = collection["id"];
    return this.Json(null);
}

回答by Chris Moschini

You can submit JSON and parse it as dynamic if you use a wrapper like so:

如果您使用这样的包装器,您可以提交 JSON 并将其解析为动态:

JS:

JS:

var data = // Build an object, or null, or whatever you're sending back to the server here
var wrapper = { d: data }; // Wrap the object to work around MVC ModelBinder

C#, InputModel:

C#,输入模型:

/// <summary>
/// The JsonDynamicValueProvider supports dynamic for all properties but not the
/// root InputModel.
/// 
/// Work around this with a dummy wrapper we can reuse across methods.
/// </summary>
public class JsonDynamicWrapper
{
    /// <summary>
    /// Dynamic json obj will be in d.
    /// 
    /// Send to server like:
    /// 
    /// { d: data }
    /// </summary>
    public dynamic d { get; set; }
}

C#, Controller action:

C#,控制器动作:

public JsonResult Edit(JsonDynamicWrapper json)
{
    dynamic data = json.d; // Get the actual data out of the object

    // Do something with it

    return Json(null);
}

Annoying to add the wrapper on the JS side, but simple and clean if you can get past it.

在 JS 端添加包装器很烦人,但如果你能通过它就简单而干净。

Update

更新

You must also switch over to Json.Net as the default JSON parser in order for this to work; in MVC4 for whatever reason they've replaced nearly everything with Json.Net except Controller serialization and deserialization.

您还必须切换到 Json.Net 作为默认 JSON 解析器才能使其正常工作;在 MVC4 中,无论出于何种原因,他们都用 Json.Net 替换了几乎所有内容,除了控制器序列化和反序列化。

It's not very difficult - follow this article: http://www.dalsoft.co.uk/blog/index.php/2012/01/10/asp-net-mvc-3-improved-jsonvalueproviderfactory-using-json-net/

这不是很困难 - 按照这篇文章:http: //www.dalsoft.co.uk/blog/index.php/2012/01/10/asp-net-mvc-3-improved-jsonvalueproviderfactory-using-json-net /

回答by Coruscate5

Much like the accepted answer of a FormCollection, dynamic objects can also map to arbitrary JSON.

与 FormCollection 的公认答案非常相似,动态对象也可以映射到任意 JSON。

The only caveat is that you need to cast each property as the intended type, or MVC will complain.

唯一的警告是您需要将每个属性转换为预期类型,否则 MVC 会抱怨。

Ex, in TS/JS:

例如,在 TS/JS 中:

var model: any = {};
model.prop1 = "Something";
model.prop2 = "2";

$http.post("someapi/thing", model, [...])

MVC C#:

MVC C#:

[Route("someapi/thing")]
[HttpPost]
public object Thing(dynamic input)
{
    string prop1 = input["prop1"];
    string prop2 = input["prop2"];

    int prop2asint = int.Parse(prop2);

    return true;
}

回答by DalSoft

Another solution is to use a dynamic type in your model. I've written a blog post about how to bind to dynamic types using a ValueProviderFactory http://www.dalsoft.co.uk/blog/index.php/2012/01/10/asp-net-mvc-3-improved-jsonvalueproviderfactory-using-json-net/

另一种解决方案是在模型中使用动态类型。我写了一篇关于如何使用 ValueProviderFactory 绑定到动态类型的博客文章http://www.dalsoft.co.uk/blog/index.php/2012/01/10/asp-net-mvc-3-improved -jsonvalueproviderfactory-using-json-net/