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条回答
倾城 Initia
2楼-- · 2020-05-15 14:17

Try this

<%:Html.TextBoxFor(m => m.FromDate, new { @Value = (String.Format("{0:dd/MM/yyyy}", Model.FromDate)) }) %>
查看更多
再贱就再见
3楼-- · 2020-05-15 14:22

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

ModelState.SetModelValue("due", new ValueProviderResult(
       due.ToShortDateString(), 
       due.ToShortDateString(), 
       null));
查看更多
Juvenile、少年°
4楼-- · 2020-05-15 14:26

I just came across this very simple and elegant solution, available in MVC 2:

http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx

Basically if you are using MVC 2.0, use the following in your view.

 <%=Html.LabelFor(m => m.due) %>
 <%=Html.EditorFor(m => m.due)%>

then create a partial view in /Views/Shared/EditorTemplates, called DateTime.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %>
<%=Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" }) %>

When the EditorFor<> is called it will find a matching Editor Template.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-05-15 14:26

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.

查看更多
Melony?
6楼-- · 2020-05-15 14:30

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.

查看更多
来,给爷笑一个
7楼-- · 2020-05-15 14:32

In order to get strongly typed access to your model in the code behind of your view you can do this:

public partial class SomethingView : ViewPage<T>
{
}

Where T is the ViewData type that you want to pass in from your Action.

Then in your controller you would have an action :

public ActionResult Something(){
    T myObject = new T();
    T.Property = DateTime.Today();

    Return View("Something", myObject);
}

After that you have nice strongly typed model data in your view so you can do :

<label>My Property</label>
<%=Html.TextBox(ViewData.Model.Property.ToShortDateString())%>
查看更多
登录 后发表回答