Question

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?

Was it helpful?

Solution

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top