Format Date On Binding (ASP.NET MVC)

后端 未结 12 737
感情败类
感情败类 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:21

    First, add this extension for getting property path:

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

    Than add this extension for HtmlHelper:

     public static MvcHtmlString DateBoxFor(
                    this HtmlHelper helper,
                    TEntity model,
                    Expression> 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

提交回复
热议问题