Search code examples
c#asp.net-mvccustom-model-binder

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?

Default value:

public void Show(Ship ship = null)
{
     // ...
}

No default value:

public void Show(Ship ship)
{
     // ...
}

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).


Solution

  • If I understand correctly, you can query whether the parameter is decorated with 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;
        }
    }