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

Gar*_*ngs 12 jquery json asp.net-mvc-3

我正在使用.Net 4,MVC 3和jQuery v1.5做一些工作

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

{ id: 1, title: "Some text", category: "test" }
Run Code Online (Sandbox Code Playgroud)

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

[Serializable]
public class myObject
{
    public int id { get; set; }
    public string title { get; set; }
    public string category { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

public void DoSomething(myObject data)
{
    // do something
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

这有可能吗?我尝试将对象映射到Dictionary,但数据的值最终会变为null.

谢谢

Bui*_*ted 15

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

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

  • 如果传回的对象具有子对象,则此解决方案变得非常混乱. (4认同)
  • @ user1477388包装的动态方法:http://stackoverflow.com/a/17050505/176877 (2认同)

Chr*_*ini 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
Run Code Online (Sandbox Code Playgroud)

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; }
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

很烦人在JS方面添加包装器,但如果你可以通过它简单而干净.

更新

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

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