views:

779

answers:

2

I would like to write my own model binder for DateTime type. First of all I'd like to write a new attribute that I can attach to my model property like:

[DateTimeFormat("d.M.yyyy")]
public DateTime Birth { get; set,}

This is the easy part. But the binder part is a bit more difficult. I would like to add a new model binder for type DateTime. I can either

  • implement IModelBinder interface and write my own BindModel() method
  • inherit from DefaultModelBinder and override BindModel() method

My model has a property as seen above (Birth). So when the model tries to bind request data to this property, my model binder's BindModel(controllerContext, bindingContext) gets invoked. Everything ok, but. How do I get property attributes from controller/bindingContext, to parse my date correctly? How can I get to the PropertyDesciptor of property Birth?

Edit

Because of separation of concerns my model class is defined in an assembly that doesn't (and shouldn't) reference System.Web.MVC assembly. Setting custom binding (similar to Scott Hanselman's example) attributes is a no-go here.

+1  A: 

I don't think you should put locale-specific attributes on a model.

Two other possible solutions to this problem are:

  • Have your pages transliterate dates from the locale-specific format to a generic format such as yyyy-mm-dd in JavaScript. (Works, but requires JavaScript.)
  • Write a model binder which considers the current UI culture when parsing dates.

To answer your actual question, the way to get custom attributes (for MVC 2) is to write an AssociatedMetadataProvider.

Craig Stuntz
It's not really related to locale-specific formatting. The problem is that DateTime must have both date and time in a string for default binder to parse it correctly. Doesn't matter which localisation is used. I just want to provide date from the client and parse it correctly to a DateTime (time set to 00:00:00) instance on model binding.
Robert Koritnik
If at all possible I'd like to avoid writing custom metadata provider. but I guess this could be exactly what I need. I could attach my own attributes to ModelMetadata information.
Robert Koritnik
It is not true that DateTime.Parse requires a string. Try `var dt = DateTime.Parse("2010-03-01");` I guarantee it works! A particular DateTime *format* might, though.
Craig Stuntz
DateTime.parse may be fine with that, DefaultModelBinder obviously isn't. My date format is the same as defined by locale anyway. I tried loading a view model with date time and displaying a strong type view that consumes it and displayed date including time. Nad when I include time in my DateTime property everything works fine. Otherwise I gave validation error (using DataAnnotations)
Robert Koritnik
I wouldn't be so sure that "`DefaultModelBinder` obviously isn't." It works fine for that, at least here. I note you're in Slovenia, so it's possible (though not *obvious*!) that a machine in a certain configuration won't parse yyyy-mm-dd, although that *should* work in any culture. But returning to the point at hand, an associated metadata provider is all of 20 lines of code or so, and will supply your binder the info you want.
Craig Stuntz
Based on metadata provider I accept your answer as the most appropriate solution. Thanks Craig.
Robert Koritnik
+2  A: 

I had this very big problem myself and after hours of try and fail I got a working solution like you asked.

First of all since having a binder on just a property is not possibile yuo have to implement a full ModelBinder. Since you don't want the bind all the single property but only the one you care you can inherit from DefaultModelBinder and then bind the single property:

public class DateFiexedCultureModelBinder : DefaultModelBinder
{
    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
    {
        if (propertyDescriptor.PropertyType == typeof(DateTime?))
        {
            try
            {
                var model = bindingContext.Model;
                PropertyInfo property = model.GetType().GetProperty(propertyDescriptor.Name);

                var value = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name);

                if (value != null)
                {
                    System.Globalization.CultureInfo cultureinfo = new System.Globalization.CultureInfo("it-CH");
                    var date = DateTime.Parse(value.AttemptedValue, cultureinfo);
                    property.SetValue(model, date, null);
                }
            }
            catch
            {
                //If something wrong, validation should take care
            }
        }
        else
        {
            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
        }
    }
}

In my example I'm parsing date with a fiexed culture, but what you want to do is possible. You should create a CustomAttribute (like DateTimeFormatAttribute) and put it over you property:

[DateTimeFormat("d.M.yyyy")]
public DateTime Birth { get; set,}

Now in the BindProperty method, instead of looking for a DateTime property you can look for a property with you DateTimeFormatAttribute, grab the format you specified in the constructor and then parse the date with DateTime.ParseExact

I hope this helps, it took me very long to come with this solution. It was actually easy to have this solution once I knew how to search it :(

Davide Vosti