动态传递JSON对象到C#MVC控制器 [英] Passing dynamic json object to C# MVC controller

查看:557
本文介绍了动态传递JSON对象到C#MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一些工作在.NET 4中,MVC 3和jQuery 1.5版

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

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

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.

{ 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
}

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

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

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

这工作得很好,我的JSON对象映射到我的C#对象。我想要做的是通过一个JSON对象,很可能会改变。当它改变,我不希望有物品,每次添加到我的C#模式JSON对象的变化。

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.

这是实际可能吗?我试图对象映射到一个字典,但数据的价值将只落得被空。

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

感谢

推荐答案

presumably接受输入只用于此特定用途,所以你可以只使用操作的的FormCollection 对象,那么你的对象的所有的JSON属性将被添加到字符串集合。

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

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

这篇关于动态传递JSON对象到C#MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆