2011-02-16 84 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/

相關問題