Format Date On Binding (ASP.NET MVC)

2020-05-15 14:02发布

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

...
<label>Due Date</label>
<%=Html.TextBox("due")%>
...

I am using a ModelBinder to bind the post to my model (the due property is of DateTime type). The problem is when I put "01/01/2009" into the textbox, and the post does not validate (due to other data being input incorrectly). The binder repopulates it with the date and time "01/01/2009 00:00:00".

Is there any way to tell the binder to format the date correctly (i.e. ToShortDateString())?

标签: asp.net-mvc
12条回答
爷、活的狠高调
2楼-- · 2020-05-15 14:05

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)
查看更多
Animai°情兽
3楼-- · 2020-05-15 14:05

I found this question while searching for the answer myself. The solutions above did not work for me because my DateTime is nullable. Here's how I solved it with support for nullable DateTime objects.

<%= Html.TextBox(String.Format("{0:d}", Model.Property)) %>
查看更多
▲ chillily
4楼-- · 2020-05-15 14:06

MVC4 EF5 View I was trying to preload a field with today's date then pass it to the view for approval.

ViewModel.SEnd = DateTime.Now    //preload todays date  
return View(ViewModel)           //pass to view

In the view, my first code allowed an edit:

@Html.EditedFor(item.SEnd)        //allow edit

Later I changed it to just display the date, the user cannot change it but the submit triggers the controller savechanges

 <td>
 @Html.DisplyFor(item.SEnd)       //show no edit
 </td>

When I changed to DisplayFor I needed to add this to ensure the preloaded value was passed back to the controller. I also need to add HiddenFor's for every field in the viewmodel.

    @Html.HiddenFor(model => model.SEnd)     //preserve value for passback.

Beginners stuff but it took a while to work this out.

查看更多
够拽才男人
5楼-- · 2020-05-15 14:08

Why don't you use

<% =Html.TextBox("due", Model.due.ToShortDateString()) %>
查看更多
贼婆χ
6楼-- · 2020-05-15 14:17

First, add this extension for getting property path:

public static class ExpressionParseHelper
{
    public static string GetPropertyPath<TEntity, TProperty>(Expression<Func<TEntity, TProperty>> property)
    {                       
         Match match = Regex.Match(property.ToString(), @"^[^\.]+\.([^\(\)]+)$");
         return match.Groups[1].Value;
    }
}

Than add this extension for HtmlHelper:

 public static MvcHtmlString DateBoxFor<TEntity>(
                this HtmlHelper helper,
                TEntity model,
                Expression<Func<TEntity, DateTime?>> property,
                object htmlAttributes)
            {
                DateTime? date = property.Compile().Invoke(model);
                var value = date.HasValue ? date.Value.ToShortDateString() : string.Empty;
                var name = ExpressionParseHelper.GetPropertyPath(property);

                return helper.TextBox(name, value, htmlAttributes);
            }

Also you should add this jQuery code:

$(function() {
    $("input.datebox").datepicker();
});

datepicker is a jQuery plugin.

And now you can use it:

<%= Html.DateBoxFor(Model, (x => x.Entity.SomeDate), new { @class = "datebox" }) %>

ASP.NET MVC2 and DateTime Format

查看更多
手持菜刀,她持情操
7楼-- · 2020-05-15 14:17

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.

查看更多
登录 后发表回答