Format Date On Binding (ASP.NET MVC)

后端 未结 12 723
感情败类
感情败类 2021-01-31 08:46

In my ASP.net MVC app I have a view that looks like this:

...

<%=Html.TextBox(\"due\")%>
...

I am usi

相关标签:
12条回答
  • 2021-01-31 09:00

    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.

    0 讨论(0)
  • 2021-01-31 09:00

    Try this

    <%:Html.TextBoxFor(m => m.FromDate, new { @Value = (String.Format("{0:dd/MM/yyyy}", Model.FromDate)) }) %>
    
    0 讨论(0)
  • 2021-01-31 09:05

    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.

    0 讨论(0)
  • 2021-01-31 09:09

    I find the best way to do this is to reset the ModelValue

    ModelState.SetModelValue("due", new ValueProviderResult(
           due.ToShortDateString(), 
           due.ToShortDateString(), 
           null));
    
    0 讨论(0)
  • 2021-01-31 09:09

    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.

    0 讨论(0)
  • 2021-01-31 09:14

    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)
    
    0 讨论(0)
提交回复
热议问题