breaking datetime into constituent parts ASP.NET MVC form
i have searched the web relentlessly for this and have not found anything - which is surprising because i would think it is such a common scenario!
Basically, on my model i have a DateTime
field which i wish the user to populat开发者_StackOverflowe through a form. I am using the Html helper to render all other parts of the form (along with validation)
So this question is in two parts...
Html Helper
Firstly, is there any way to use the Html helper to split the DateTime
field to be rendered as the three constituent parts of a date: day, month, year (since i do not care about the time part). This could be rendered as text boxes, drop down lists or a combination of both.
Model Binding
And then when the form is posted, what is the best approach for binding back up to the model? I have seen Scott Hanselmann's solution to this, but it seems a little bloated for what i need - i was hoping for a slightly more elegant solution. Is it recommended to extend DefaultModelBinder
and set that as default binder (since all dates would be handled in this way) or write a class that implements IModelBionder
and set it as the default binder for the DateTime
type?
Thanks for all the help in advance :-) i'm loving MVC but it's infuriating me that something so trivial is causing so much headaches!
think i've worked out a decent solution to this, so i will provide an answer for any who stumble across this in future!
With regards to the Html helper, i somehow completely overlooked creating an extension method! So eventually when it occurred to me, i wrote an extension method which basically makes calls to other methods of the Html helper to provide three fields (whether you use drop down of text inputs is your choice)
public static string DateTime(this HtmlHelper helper, string name)
{
StringBuilder builder = new StringBuilder();
string dayName = name + ".Day";
string monthName = name + ".Month";
string yearName = name + ".Year";
builder.Append(helper.TextBox(dayName));
builder.Append(helper.DropDownList(monthName, typeof (Months)));
builder.Append(helper.TextBox(yearName));
return builder.ToString();
}
As for the binding after a form post, i simply created a class which implemented IModelBinder
and set it as default for DateTime
type on application start. This can then be overridden at a controller action level should a different method of binding be required. This was essentially a simpler version of Scott's binder which i linked to in my question.
Works like a charm at the moment (if a little simplistic), but i'm sure it'll be enough of a foundation for anyone else who is mystified by this problem!
精彩评论