Michael
Michael

Reputation: 13616

The action method is fired, but value of the passed parameter is null

I use ASP MVC 5. I try to send data from client to action method on the server.

Here is data that I sent:

  var layer = { 
                layeType:"Vector"
                layerName:"aaaa"
                mapId:5
               }

And here is ajax method:

function saveLayer(layer, callback, error) {
    return $.ajax({
        url: '/Mobile/Layer/SaveLayer',
        type: "GET",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: { layer: layer },
        success: callback,
        error: error
    });

Here is action method:

 public JsonResult SaveLayer(string layer) 
        {         
           return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
        }

The action method is fired, but value of the layer is null.

Any idea why value is null and how to fix it?

Upvotes: 0

Views: 44

Answers (2)

Rajdeep
Rajdeep

Reputation: 802

First -

Make the type from GET to POST

Second -

Change the parameter type from string to Object type, i.e. Layer

The properties in Layer class should match the json data you are sending.

public JsonResult SaveLayer(Layer layer) 
{         
  return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
}

Upvotes: 0

Slicksim
Slicksim

Reputation: 7172

Ok,

Firstly, you are trying to send a complex object through on a GET request. GET requests don't have a body, they are limited to transferring data through the Url, so it would need to be a query string parameter.

Secondly, following rest conventions, GETs are idempotent, in that, each action should not have a side effect, calling it repeatedly should yield the same result.

I would switch your method to a POST, as that will more accurately convey that you are going to be causing a side effect on the server.

After you have done that, I would make a model in C# that matches the json structure that you are passing in, then you will get a value through.

Class

public class Layer 
{
    public string LayeType {get;set;}
    public string LayerName {get;set;}
    public int MapId {get;set;}

}

Javascript

function saveLayer(layer, callback, error) {
return $.ajax({
    url: '/Mobile/Layer/SaveLayer',
    type: "POST",
    async: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: { layer: layer },
    success: callback,
    error: error
});

Function

public JsonResult SaveLayer(Layer layer) 
{         
   return Json(new { Result = "OK" }, JsonRequestBehavior.AllowGet);
}

That should sort it

Upvotes: 1

Related Questions