ASP.Net MVC Model Binding Complex Object using GET

前端 未结 3 1958
生来不讨喜
生来不讨喜 2021-02-20 17:48

I have a class in my web project:

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

which is a

相关标签:
3条回答
  • 2021-02-20 18:17

    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.

    0 讨论(0)
  • 2021-02-20 18:35

    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);
    }
    
    0 讨论(0)
  • 2021-02-20 18:39

    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.");
    });
    
    0 讨论(0)
提交回复
热议问题