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

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

问题描述

我正在使用 .Net 4、MVC 3 和 jQuery v1.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 的 .ajax 方法传递对象,如下所示:

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 对象.当它发生变化时,我不想在每次 JSON 对象发生变化时都将项目添加到我的 C# 模型中.

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.

谢谢

推荐答案

据推测,接受输入的操作仅用于此特定目的,因此您可以只使用 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天全站免登陆