使用GET的ASP.Net MVC模型绑定复杂对象

时间:2014-01-07 20:26:23

标签: c# javascript asp.net-mvc angularjs model-binding

我的网络项目中有一个课程:

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

这是我的控制器方法中的一个参数:

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

如果我使用POST调用方法,模型绑定会自动生效(我在js侧使用angular,这可能无关紧要):

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

如果我使用GET,则控制器中的参数始终为空。

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

使用默认模型绑定器的复杂模型绑定是否仅适用于POST,或者我可以做些什么来使其与GET一起使用?

3 个答案:

答案 0 :(得分:10)

答案是肯定的。 GET和POST请求之间的区别在于POST主体可以具有内容类型,因此可以在服务器端将它们正确解释为XML或Json,依此类推;对于GET来说,你所拥有的只是一个查询字符串。

答案 1 :(得分:8)

使用ASP.NET MVC,您确实可以在GET请求上绑定模型,只要您具有与Model类的属性名称相同的查询字符串参数名称。此answer的示例:

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

你可以像这样做一个Get请求

MyAction?Name=jon&Loc=America

并且MVC将自动绑定您的模型:

[HttpGet]
public ViewResult MyAction(ViewModel model)
{
    // Do stuff
    return View("ViewName", model);
}

答案 2 :(得分:-2)

为什么要在POST中调用属性“data”,在GET中调用“params”?两者都应称为“数据”。

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