Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

I have a complex JSON object which is sent to the View without any issues (as shown below) but I cannot work out how Serialize this data back to a .NET object when it is passed back to the controller through an AJAX call. Details of the various parts are below.

   var ObjectA = {         "Name": 1,         "Starting": new Date(1221644506800),          "Timeline": [             {                 "StartTime": new Date(1221644506800),                 "GoesFor": 200              }             ,             {                 "StartTime": new Date(1221644506800),                 "GoesFor": 100              }          ]     }; 

I am not sure how this object can be passed to a Controller Method, I have this method below where the Timelines object mirrors the above JS object using Properties.

public JsonResult Save(Timelines person) 

The jQuery I am using is:

        var encoded = $.toJSON(SessionSchedule);          $.ajax({             url: "/Timeline/Save",             type: "POST",             dataType: 'json',             data: encoded,             contentType: "application/json; charset=utf-8",             beforeSend: function() { $("#saveStatus").html("Saving").show(); },             success: function(result) {                 alert(result.Result);                 $("#saveStatus").html(result.Result).show();             }         }); 

I have seen this question which is similar, but not quite the same as I am not using a forms to manipulate the data. How to pass complex type using json to ASP.NET MVC controller

I have also seen references to using a 'JsonFilter' to manually deserialize the JSON, but was wondering if there is a way to do it nativly though ASP.NET MVC? Or what are the best practices for passing data in this way?

like image 800
Rosstified Avatar asked Feb 18 '09 10:02

Rosstified


People also ask

How pass data from JSON in asp net?

Create target "JSON object Mapper" object class file according to the business requirements. Create a "Controllers\HomeController. cs" file with default Index method and GetData(...) method with string type input query parameters for Ajax call with following lines of code i.e.

How pass JSON data in MVC?

Make sure you specify POST type, as ajax method uses GET method by default. MVC Controller: Decorate the Action method with HttpPost verb. This action method will only handle http post request from browser. Ajax submission from the browser will be automatically deserialized to FormData c# class as a poco.

Can we send data from view to controller in MVC?

This blog will discuss four (4) common ways to pass data from the view to the controller: Passing by Typed Arguments. Request Object. Form Collections Object.


2 Answers

Edit:

This method should no longer be needed with the arrival of MVC 3, as it will be handled automatically - http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx


You can use this ObjectFilter:

    public class ObjectFilter : ActionFilterAttribute {      public string Param { get; set; }     public Type RootType { get; set; }      public override void OnActionExecuting(ActionExecutingContext filterContext) {         if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json")) {             object o =             new DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);             filterContext.ActionParameters[Param] = o;         }      } } 

You can then apply it to your controller methods like so:

    [ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]     public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... } 

So basically, if the content type of the post is "application/json" this will spring into action and will map the values to the object of type you specify.

like image 193
ChadT Avatar answered Sep 19 '22 13:09

ChadT


You say "I am not using a forms to manipulate the data." But you are doing a POST. Therefore, you are, in fact, using a form, even if it's empty.

$.ajax's dataType tells jQuery what type the server will return, not what you are passing. POST can only pass a form. jQuery will convert data to key/value pairs and pass it as a query string. From the docs:

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

Therefore:

  1. You aren't passing JSON to the server. You're passing JSON to jQuery.
  2. Model binding happens in the same way it happens in any other case.
like image 32
Craig Stuntz Avatar answered Sep 18 '22 13:09

Craig Stuntz