2011-02-16 78 views
11

我做了一些工作在.NET 4中,MVC 3和jQuery V1.5动态传递JSON对象到C#MVC控制器

我有一个JSON对象,可根据其网页呼吁改变它。我想将对象传递给控制器​​。

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

我明白,如果我创建一个自定义模式,如

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

,并在我的控制器使用这个功能,比如

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

和使用jQuery的阿贾克斯方法一样传递对象这个:

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

这工作正常,我的JSON对象映射到我的C#对象。我想要做的是通过一个可能会改变的JSON对象。当它发生变化时,我不希望每次JSON对象更改时都要将项目添加到我的C#模型中。

这实际上可行吗?我试图将对象映射到字典,但数据的值将最终为空。

感谢

+0

相关的/欺骗:http://stackoverflow.com/questions/5473156/how-to-get-a-dynamically-created-json-data -set-in-mvc-3-控制器 http://stackoverflow.com/questions/10787679/passing-unstructured-json-between-jquery-and-mvc-controller-actions – 2013-01-07 10:14:33

回答

14

大概只用于接受输入的行动为这个特定的目的,所以你可以只使用FormCollection对象,那么你的对象的所有JSON属性将被添加到字符串集合。

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

辉煌,这样一个简单而有效的答案。谢谢 – 2011-02-17 09:54:52

+4

如果传回的对象有子对象,则此解决方案变得非常混乱。 – 2013-01-06 23:54:36

+0

@ChrisMoschini如果对象有子对象,你会怎么做? – user1477388 2013-06-11 17:20:59

3

使用自定义ModelBinder,您可以接收JsonValue作为操作参数。这基本上会给你一个动态类型的JSON对象,可以在你想要的任何形状的客户端上创建。该技术在this博客文章中概述。

9

您可以提交JSON和解析它的动态,如果你使用的包装,像这样绑定到动态类型:

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:

/// <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#,控制器动作:

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

    // Do something with it 

    return Json(null); 
} 

讨厌在JS端添加包装,但如果你可以通过它简单和干净。

更新

还必须切换到Json.Net为默认的JSON解析器为了这个工作;在MVC4中,无论出于何种原因,除了Controller序列化和反序列化外,他们几乎用Json.Net取代了所有内容。

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

相关问题