开发者

Merge POST parameters in single property in my view model

In my registration FORM, I have to allow the user to put his date of birth. It is a requirement, that I show a SELECT for the d开发者_JAVA百科ay, a SELECT for the month and a SELECT for the year.

I have worked out a Html helper extension that creates that schema, and names the controls propertyName+".day", propertyName+".month" and propertyName+".year".

The idea is that in my view model, I define a DateTime property and then invoke this helper: @Html.DateSelect(m=>m.DateOfBirth) , but the problem is that I don't know how to merge the previous 3 properties in a DateTime again.

I would get 3 POST parameters named dateofbirth.day, dateofbirth.month and dateofbirth.year.

How would it be done in MVC3?

Thanks


You could write a custom model binder.


You will need to use a custom model binder:

public class SplitDateTimeBinder : IModelBinder 
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {

        ValueProviderResult day = bindingContext.ValueProvider.GetValue("propertyName.day");
        ValueProviderResult month = bindingContext.ValueProvider.GetValue("propertyName.month");
        ValueProviderResult year = bindingContext.ValueProvider.GetValue("propertyName.year");

        DateTime result = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day));

        return user;
    }
}

and register it in Global.asax:

ModelBinders.Binders.Add(typeof(DateTime), new SplitDateTimeBinder());

I've used int.Parse() in the example but you'll probably want to use int.TryParse() and handle failed parses properly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜