[英]ASP.Net MVC Model Binding Complex Object using GET
我的web项目中有一个类:
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,则控制器中的参数始终为null。
$http({
method: "get",
url: controllerRoot + "TheControllerMethod",
params: {
myParam: myParam
}
}).success(function (data) {
callback(data);
}).error(function () {
alert("Error getting my stuff.");
});
使用默认模型绑定器的复杂模型绑定是否仅适用于POST,或者我可以做些什么来使其与GET一起工作?
答案是肯定的。 GET和POST请求之间的区别在于POST主体可以具有内容类型,因此可以在服务器端将它们正确解释为XML或Json,依此类推; 对于GET,你所拥有的只是一个查询字符串。
使用ASP.NET MVC,您确实可以在GET请求上绑定模型, 只要您具有与Model类的属性名称相同的查询字符串参数名称 。 这个答案的例子:
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);
}
你为什么要在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.");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.