[英]Optional Parameters in C# - Defaulting a user-defined Class to null
在C#控制器中,我有一個使用可選參數定義的函數,該參數默認設置為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
);
默認模型綁定器(DefaultModelBinder)將創建CustomFilterModel的實例,然后嘗試使用請求中的數據填充對象。 即使默認模型綁定器在請求中找不到模型的屬性,它仍將返回空模型,因此您永遠不會獲得參數的空對象。 源[1]中似乎沒有任何東西會返回null模型。
[1] https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Mvc/DefaultModelBinder.cs
這是DefaultModelBinder
的替代品:
public class OptionalClassInstanceBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
bindingContext.FallbackToEmptyPrefix = false;
return base.BindModel(controllerContext, bindingContext);
}
}
[ModelBinder(typeof(OptionalClassInstanceBinder))]
public class CustomFilterModel
{
...
}
請注意,盡管使用了綁定器,您必須將參數名稱作為任何內部屬性的前綴,例如?filter.range=1
而不是?range=1
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.