[英]Does an action parameter have a default value?
How can I find out in a custom ModelBinder in ASP.NET MVC whether I am binding to a parameter that has a default value or not? 如何在ASP.NET MVC的自定义ModelBinder中找出我是否绑定到具有默认值的参数?
Default value: 默认值:
public void Show(Ship ship = null)
{
// ...
}
No default value: 无默认值:
public void Show(Ship ship)
{
// ...
}
ModelBinder: ModelBinder:
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;
}
}
}
I want to know this because I want to show an error message if a user does a request to an action and does not provide all necessary information (which would be all parameters that have no default value). 我想知道这一点,因为如果用户对某项操作提出请求并且未提供所有必要的信息(将是没有默认值的所有参数),那么我将显示一条错误消息。
I don't think there is any efficient or reasonable way to tell if a method input parameter has a default value. 我认为没有任何有效或合理的方法来判断方法输入参数是否具有默认值。 If you're looking for a way to ensure the incoming data is proper, you would want to bind the view form fields to a model and use ModelState.IsValid to test if all fields have data. 如果您正在寻找一种确保输入数据正确的方法,则需要将视图表单字段绑定到模型并使用ModelState.IsValid来测试所有字段是否都包含数据。
A great introduction can be found here: http://www.codeproject.com/Articles/710776/Introduction-to-ASP-NET-MVC-Model-Binding-An-Absol 可以在这里找到出色的介绍: http : //www.codeproject.com/Articles/710776/Introduction-to-ASP-NET-MVC-Model-Binding-An-Absol
If I understand correctly, you can query whether the parameter is decorated with OptionalAttribute
如果我理解正确,则可以查询该参数是否用OptionalAttribute
装饰
var method = typeof(YourClassName).GetMethod("Show");
foreach (var pi in method.GetParameters())
{
var optionalAttribute = pi.GetCustomAttributes<OptionalAttribute>().FirstOrDefault();
if (optionalAttribute != null)
{
//This is optional parameter
object defaultValue = pi.DefaultValue;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.