1

I'm rendering an input control which holds a DateTime value:

[DataType(DataType.Date)]
public DateTime? ScheduledDateTime { get; set; }

The formatting applied to the input is stored as a user preference which is retrieved from the database at runtime.

So, I've got the following value at run-time:

YYYY-MM-DD

The actual formatting not-withstanding, how can I tell my model binder to format the DateTime as specified? All examples I've found rely on setting the DateFormatString attribute, but this is only able to be set with a compile time constant. This makes it unusable for my purposes.

Something with override the default model binder? Anyone got an example, I haven't been able to turn one up Googling.

EDIT: Maybe I create a new HtmlHelper which will handle the conversion at runtime?

EDIT2: Pretty sure I'm going to go about it like this. Pardon the overly verbose naming convention:

<%= Html.TextBoxFor(model => model.ScheduledDateTime, string.Format("{0:" + User.GetDateFormatStringAsCSharpFormat(SessionManager.Default.User.DateFormat)+ "}", Model.ScheduledDateTime))%>

1 Answer 1

3

This uses Razor syntax but same principle applies

@{
  var dateFormat = (DateTime)Viewbag.PreferredDateFormatForUser //Just grab it from where ever you have it
}


@Html.TextBox("ScheduleDateTime", model.ScheduleDateTime.ToString(dateFormat))

Here is the reference for custom date time format strings

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Sign up to request clarification or add additional context in comments.

1 Comment

Yep. This is what I'm doing just in other syntax. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.