Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

It occurs to me that the ModelBinder mechanism in ASP MVC

public interface IModelBinder {
  object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext);
}

Is insanely powerful. What are some cool uses of this mechanism that you've done/seen?

I guess since the concept is similar in other frameworks there's no reason to limit it to Asp Mvc

share|improve this question
add comment

2 Answers

Consider a custom type called TimeInterval that is stored as a double, but is displayed as hh.mm.ss.ffffff where ffffff is fractional seconds. With custom binding, it is possible to show the binder how to properly parse and display these numbers, without having to write custom code in the controller.

// This class implements a custom data type for data binding.
public class TimeInterval
{
    double _value;

    // Constructor
    public TimeInterval(string value)
    {
        // Extension method parses hh.mm.ss.ffffff string value to double.
        _value = value.ToSeconds();
    }
    // Constructor
    public TimeInterval(double value)
    {
        _value = value;
    }
    public string GetText()
    {
        // Extension method formats double value as hh.mm.ss.ffffff time string.
        return _value.ToTimeString();
    }
    public double? GetValue()
    {
        return _value;
    }
}

// This class implements custom binding for the TimeInterval custom type.  
// It is registered in Global.asax 
public class TimeIntervalBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        string value = GetAttemptedValue(bindingContext);

        if (value == "")
            return null;

        return new TimeInterval(value);
    }

    private static string GetAttemptedValue(ModelBindingContext context)
    {
        ValueProviderResult value = context.ValueProvider[context.ModelName];
        return value.AttemptedValue ?? string.Empty;
    }
}

// in Global.asax:
protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    ModelBinders.Binders.Add(typeof(TimeInterval), new TimeIntervalBinder());
}

Now binding happens automatically for the new custom type.

share|improve this answer
add comment

I've used model binders to localize content based on session state information. By the time the controller knows anything, the content has already been set according to the user's preferred locale.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.