【发布时间】:2014-07-14 18:40:42
【问题描述】:
如何在 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;
}
}
}
我想知道这一点,因为如果用户对某个操作发出请求并且未提供所有必要信息(这将是所有没有默认值的参数),我想显示一条错误消息。
【问题讨论】:
-
if (ship == null) { // 没有信息 } else { // 有信息 } ,我觉得有用吗?这里有什么问题?
-
你能把代码显示在你想知道的地方吗?您的 binder 何时调用模型上的方法?
-
@Aaron:检查应该在模型绑定器中自动执行,这样我们就不必检查每个操作方法。
-
@CodeCaster:更新问题以包含示例代码。
-
什么你想在那里测试可选?
标签: c# asp.net-mvc custom-model-binder