2014-01-07 137 views
8

我有一个类在我的web项目的复杂对象:ASP.Net MVC模型绑定使用GET

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

这是在我的控制器方法的参数:

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

如果我调用该方法使用POST,模型自动绑定工作(我在JS一面,这可能不要紧使用角):

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

是否使用默认的模型绑定只上岗工作的复杂模型的结合,或者是有什么我可以做,以使这一工作得到什么?

+3

我认为简单的答案是肯定的,你只能发布复杂类型。你可以做一个复杂类型的get请求,但需要将它序列化到查询字符串soemhow –

回答

10

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

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

在ASP.NET MVC,你确实可以,只要你有相同的查询字符串参数的名称作为模型类的属性名称的绑定模型上的GET请求,。从这个answer例如:

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

你可以这样做

MyAction?Name=jon&Loc=America 

Get请求和MVC将自动绑定模型:

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