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?

2
  • 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 Commented Jan 7, 2014 at 20:29
  • See example in stackoverflow.com/questions/47931625/… Commented Apr 14, 2018 at 22:13

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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);
}

Comments

-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.");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.