Reputation: 73112
I've got an action with a signature like this:
public ActionResult Index([ModelBinder(typeof(MyEnumModelBinder))] MyEnum myEnum)
Which is implemented like this:
public class MyEnumModelBinder: IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue("myEnum");
return valueProviderResult == null ?
MyEnum.Default :
valueProviderResult.AttemptedValue.ToMyEnum();
}
}
Basically, i'm binding a raw value to an enum, pretty simple. Works fine.
But, notice how in order to get access to the attempted value, i need to use a magic string ("myEnum").
Is there any way i can supply this to the model binder, so remove the magic string?
Because if i want to use this model binder in other places, then i have to make sure i call the parameter "myEnum", otherwise it will cause a runtime error.
I tried adding a ctor to the model binder, but there's nowhere where i actually instantiate it.
Any ideas?
Upvotes: -1
Views: 2123
Reputation: 1038770
Is there any way i can supply this to the model binder, so remove the magic string?
Sure:
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
Upvotes: 1