up vote 1 down vote favorite
share [g+] share [fb]

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

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
}

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

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

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.

Thanks

link|improve this question
feedback

3 Answers

up vote 5 down vote accepted

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);
    }
link|improve this answer
Brilliant, such a simple yet effect answer. Thanks – Gareth Hastings Feb 17 '11 at 9:54
feedback

Using a custom ModelBinder, you could receive a JsonValue as an action parameter. This would basically give you a dynamically typed JSON object that can be created on the client with whatever shape you wish. This technique is outlined in this blog post.

link|improve this answer
Thanks for your post, the blog post you linked was very interesting to read and would have also covered my issue. I marked the other answer though as it was nice and simple. – Gareth Hastings Feb 17 '11 at 9:55
Thanks for the followup. I totally agree BTW. =) – Ray Vernagus Feb 17 '11 at 12:33
feedback

Another solution is to use a dynamic type in your model. I've written a blog post about how to bind to dynamic types using a ValueProviderFactory http://www.dalsoft.co.uk/blog/index.php/2012/01/10/asp-net-mvc-3-improved-jsonvalueproviderfactory-using-json-net/

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.