-1

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?

Eric J.
  • 147,927
  • 63
  • 340
  • 553
RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • I'm affraid there is no easy way out of this. What you're really asking is how to get the parameter name. Reflection simply doesn't expose this. – Polity Feb 21 '12 at 03:09

1 Answers1

1

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);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928