I use ASP.NET MVC and jQuery to save some data through AJAX calls. I am currently passing some JSON data using the jQuery ajax () function, e.g.
$.ajax({ dataType: 'json', type: 'POST', url: '@Url.Action("UpdateName", "Edit")', data: { id: 16, name: 'Johnny C. Bad' } });
using this controller method and helper class.
public void UpdateName(Poco poco) { var person = PersonController.GetPerson(poco.Id); person.Name = poco.Name; PersonController.UpdatePerson(person); } public class Poco { public int Id { get; set; } public string Name { get; set; } }
Another way to accept JSON data is to simply use a few arguments like this
public void UpdateName(int id, string name) { var person = PersonController.GetPerson(id); person.Name = name; PersonController.UpdatePerson(person); }
This approach is suitable for fewer arguments, but my real world code usually has about 5-10 arguments. Using an object instead of having to declare and use all of these arguments is very convenient.
I wonder if there is another way to accept JSON data as a single object and not declare a class for each controller method in which I want to use this approach. For example, something like this:
public void UpdateName(dynamic someData) { var person = PersonController.GetPerson(someData.Id); person.Name = someData.Name; PersonController.UpdatePerson(person); }
source share