0

Is it possible to create a generic Mvc controller that catches any simple Json object from a web page post and can then be interrogated for keys/values, eg

public JsonResult SaveData(Dictionary<String, Object> rs)
        {
        PersonObject obj= new PersonObject();
        foreach (string Key in rs.Keys){
           if (Key == "name")
               obj.Name=rs[Key];
      }       

    }

My web page does something like this :
    var obj={"name" : "blah", "age": 38, "gender" : "lady"};
    $.post('SaveControler/saveData', obj, function(d){});

I basically don't want to keep constructing custom view models for each entity, just have some generic code for each controller action that can use reflection to populate objects.

Programnik
  • 1,449
  • 1
  • 9
  • 13

2 Answers2

0

Controller :

public ActionResult About(string rs)
        {

            var values = JsonConvert.DeserializeObject<Dictionary<String, Object>>(rs);
            return Json(values);
        }

Jquery:

var obj = { "name": "blah", "age": 38, "gender": "lady" };
            $.post('@Url.Action("About")', { rs: JSON.stringify(obj) }, function (d) {
                debugger;
            });

for more info have look at James Newton answer

Arvind Maurya
  • 910
  • 12
  • 25
0

You can receive JSON as object and then deserialize it by type:

public ActionResult About(object rs)
{
   string JsonString = rs.Tostring();  
   var _PersonObject =  JsonConvert.DeserializeObject<Person>(JsonString);
}
Tee
  • 81
  • 4