在C# Controller 中,我有一个函数,该函数定义了一个可选参数,该参数默认设置为null(请参见下面的代码示例)。第一次加载页面时,将调用该函数,并且将过滤器作为初始化的对象传递,尽管默认值为null。我希望页面第一次加载时为null。有没有办法做到这一点?
public ActionResult MyControllerFunction(CustomFilterModel filter = null)
{
if (filter == null)
doSomething(); // We never make it inside this "if" statement.
// Do other things...
}
此操作由以下路由定义解决:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Project", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
最佳答案
默认的模型绑定(bind)器(DefaultModelBinder)将创建CustomFilterModel的实例,然后尝试使用请求中的数据填充对象。即使默认模型联编程序在请求中未找到模型的属性,它仍将返回空模型,因此,您将永远不会为参数获取空对象。在源[1]中似乎没有任何东西将返回空模型。
[1] https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Mvc/DefaultModelBinder.cs
关于c# - C#中的可选参数-将用户定义的类默认为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24919564/