In my ASP.net MVC app I have a view that looks like this:
...
<%=Html.TextBox(\"due\")%>
...
I am usi
I guess personally I'd say its best or easiest to do it via a strongly typed page and some defined model class but if you want it to be something that lives in the binder I would do it this way:
public class SomeTypeBinder : IModelBinder
{
public object GetValue(ControllerContext controllerContext, string modelName,
Type modelType, ModelStateDictionary modelState)
{
SomeType temp = new SomeType();
//assign values normally
//If an error then add formatted date to ViewState
controllerContext.Controller.ViewData.Add("FormattedDate",
temp.Date.ToShortDateString());
}
}
And then use that in the view when creating the textbox i.e. :
<%= Html.TextBox("FormattedDate") %>
Hope that helps.
Try this
<%:Html.TextBoxFor(m => m.FromDate, new { @Value = (String.Format("{0:dd/MM/yyyy}", Model.FromDate)) }) %>
It's a dirty hack, but it seems to work.
<%= Html.TextBoxFor(model => model.SomeDate,
new Dictionary<string, object> { { "Value", Model.SomeDate.ToShortDateString() } })%>
You get the model binding, and are able to override the HTML "value" property of the text field with a formatted string.
I find the best way to do this is to reset the ModelValue
ModelState.SetModelValue("due", new ValueProviderResult(
due.ToShortDateString(),
due.ToShortDateString(),
null));
This worked for me: mvc 2
<%: Html.TextBoxFor(m => m.myDate, new { @value = Model.myDate.ToShortDateString()}) %>
Simple and sweet!
A comment of user82646, thought I'd make it more visible.
Decorate the property in your model with the DataType
attribute, and specify that its a Date
, and not a DateTime
:
public class Model {
[DataType(DataType.Date)]
public DateTime? Due { get; set; }
}
You do have to use EditorFor
instead of TextBoxFor
in the view as well:
@Html.EditorFor(m => m.Due)