简体   繁体   中英

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

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.

A great introduction can be found here: 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

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM