如何在 ASP.NET MVC 的自定义 ModelBinder 中找出我是否绑定到具有默认值的参数?
默认值:
public void Show(Ship ship = null)
{
// ...
}
无默认值:
public void Show(Ship ship)
{
// ...
}
模型绑定器:
public class ModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var modelType = bindingContext.ModelType;
// Is it an item from the database?
if (typeof(IDbObject).IsAssignableFrom(modelType))
{
// Get from database...
var result = BindValue();
if (result == null && NotOptional()) // Code for NotOptional needed
throw new Exception();
return result;
}
}
}
我想知道这一点,因为如果用户对某个操作发出请求并且没有提供所有必要的信息(这将是所有没有默认值的参数),我想显示一条错误消息。