Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

jquery - Passing dynamic json object to C# MVC controller

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...