Format Date On Binding (ASP.NET MVC)

后端 未结 12 743
感情败类
感情败类 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.

提交回复
热议问题