10

I have a class in my web project:

public class MyClass
{
    public int? Param1 { get; set; }
    public int? Param2 { get; set; }
}

which is a parameter in my controller method:

public ActionResult TheControllerMethod(MyClass myParam)
{
    //etc.
}

If I call the method using POST, the model binding works automatically (I use angular on the js side, which likely doesn't matter):

$http({
    method: "post",
    url: controllerRoot + "TheControllerMethod",
    data: {   
        myParam: myParam
    }
}).success(function (data) {
    callback(data);
}).error(function () {
    alert("Error getting my stuff.");
});

If I use a GET, the parameter is always null in the controller.

$http({
    method: "get",
    url: controllerRoot + "TheControllerMethod",
    params: {   
        myParam: myParam
    }
}).success(function (data) {
    callback(data);
}).error(function () {
    alert("Error getting my stuff.");
});

Does complex model binding using the default model binder only work for POSTs, or is there something I can do to make this work with a GET?

Phil Sandler
  • 27,544
  • 21
  • 86
  • 147
  • 3
    I believe the simple answer is yes, you can only post a complex type. You could do a get request with a complex type but would need to serialise it onto the querystring soemhow – undefined Jan 07 '14 at 20:29
  • See example in https://stackoverflow.com/questions/47931625/pass-a-list-of-complex-object-in-query-string-to-web-api – Michael Freidgeim Apr 14 '18 at 22:13

3 Answers3

10

The answer is Yes. The difference between GET and POST requests is that a POST body can have a content type so they can be interpreted correctly on the server side as XML, or Json, so on; for GET, all you have is just a querystring.

Lin
  • 15,078
  • 4
  • 47
  • 49
8

With ASP.NET MVC you can indeed bind your model on a GET request, as long as you have the same query string parameter names as of the property names of your Model class. Example from this answer:

public class ViewModel
{
  public string Name { set;get;}
  public string Loc{ set;get;}
}

You can do a Get request like this

MyAction?Name=jon&Loc=America

and MVC will automatically bind your model:

[HttpGet]
public ViewResult MyAction(ViewModel model)
{
    // Do stuff
    return View("ViewName", model);
}
Community
  • 1
  • 1
Beyers
  • 8,968
  • 43
  • 56
-2

Why are you calling the property "data" in the POST, and "params" in the GET? Both should be called "data".

$http({
    method: "get",
    url: controllerRoot + "TheControllerMethod",
    data: {   
        myParam: myParam
    }
}).success(function (data) {
    callback(data);
}).error(function () {
    alert("Error getting my stuff.");
});
Xavier J
  • 4,326
  • 1
  • 14
  • 25