我遇到了以下问题:
我有一个带有引用类型作为参数的 asp.net mvc 5 Controller :
[Route("")]
[HttpGet]
public ActionResult GetFeeds(Location location)
{
if (location == null)
{
// init location or smth
}
// Do smth with location
return new EmptyResult();
}
您会注意到我正在使用 AttributeRouting。没有其他方法具有此操作的名称。
但是 - 这是我的位置类:
public class Location : ILocation
{
public DbGeography Coordinates { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
}
这里没什么特别的(接口(interface)定义了所有这些属性)。
如果我正在访问 Controller 操作(实际上使用 powershell)并传递如下内容:
http://localhost:2000/Feed?latitude=23.1&longitude=37
一切正常,但如果我正在使用
http://localhost:2000/Feed
location 参数不为空(它是一个具有默认值的新 Location),这是我想要的行为 :( 。
有人知道为什么会这样吗?
提前致谢
最佳答案
MVC 模型绑定(bind)程序已接管。我最初发布的内容适用于不通过模型 Binder 的实例。然而,based on other answers on SO和我自己的快速测试,由于 Binder 的工作方式和绑定(bind)属性以形成值,看来 viewmodel 参数永远不会为 null。
在您的示例中,我会检查纬度和经度是否都为空,以查看是否未通过任何内容。这意味着您需要让它们在您的 ViewModel 上可以为空
public class Location : ILocation
{
public DbGeography Coordinates { get; set; }
public double? Latitude { get; set; }
public double? Longitude { get; set; }
}
更新 Controller 代码
if (location.Latitude == null && location.Longitude == null)
{
// init location or smth
}
关于c# - Controller 参数不会变为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20689336/