在 C# Controller 中,我定义了一个函数,该函数定义了一个默认设置为 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/