c# - Controller 参数不会变为空

标签 c# asp.net-mvc controller

我遇到了以下问题:

我有一个带有引用类型作为参数的 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/

相关文章:

javascript - 在页面上显示当前月份

c# - Google Tag Manager 服务器端跟踪 .NET

c# - 我可以直接使用 Entity Framework 生成的模型吗?

macos - 将对象添加到 NSDictionaryController

html - ruby rails : Adding a second custom view to a controller (Rails 3)

controller - 基类中的 ExecuteCore() 在 MVC 4 beta 中未触发

c# - smtp.live.com - 邮箱不可用。服务器响应为 : 5. 7.3 请求的操作已中止;用户未通过身份验证

c# - 在父页面更新面板占位符中动态加载新的用户控件

c# - 如何在没有依赖注入(inject)的情况下访问 INodeServices

asp.net-mvc - T4MVC 没有生成常量?