How to format a value in a strong typed view when using ASP.Net MVC Html.TextBoxFor

I am trying to format the date provided by ASP.Net MVC TextBox to use a strongly typed view value. The date is null, so if it is zero, I want to see an empty value, otherwise I want to see it in the format MM / dd / yyyy.

<%= Html.TextBoxFor(model => model.BirthDate, new { style = "width: 75px;" })%> 

Thank,
Paul Sperantza

+17
format asp.net-mvc html-helper
Jan 18
source share
11 answers

You can save strong typing with a custom editor template and Html.EditorFor() instead of Html.TextBoxFor() .

Create a new EditorTemplates folder in the / Views / Shared folder and add a new MVC 2 View control named DateTime.ascx. Add the following

 <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.DateTime?>" %> <%= Html.TextBox("", (Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : string.Empty)) %> 

Then in your view use

 <%= Html.EditorFor(model => model.BirthDate)%></p> 

Don't worry about "", naming will still work correctly.

If you display DateTime in a different culture format for the default application culture, you need to change the culture information or create a custom mediator so that model binding works when sending DateTime.

+25
Jan 15 2018-11-15T00:
source share

MVC4 http://msdn.microsoft.com/en-us/library/hh833694.aspx

 @Html.TextBoxFor(model => model.YOUR_DATE, "{0:MM/dd/yyyy}") 
+10
Jan 25 '13 at 19:51
source share

First add this extension to get the property path:

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

Then add the extensions for the HtmlHalper:

 public static MvcHtmlString DateBoxFor<TEntity>( this HtmlHelper helper, TEntity model, Expression<Func<TEntity, DateTime?>> property, object htmlAttributes) { DateTime? date = property.Compile().Invoke(model); // Here you can format value as you wish var value = date.HasValue ? date.Value.ToShortDateString() : string.Empty; var name = ExpressionParseHelper.GetPropertyPath(property); return helper.TextBox(name, value, htmlAttributes); } 

You should also 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" }) %> 
+4
Feb 11 2018-10-11T00
source share

This is a dirty hack, but it seems to work.

 <%= Html.TextBoxFor(model => model.SomeDate, new Dictionary<string, object> { { "Value", Model.SomeDate.ToShortDateString() } })%> 

You get a binding to the model and you can override the HTML "value" property in a text box with a formatted string.

+2
Feb 22 2018-10-22T00
source share

You can consider the following sample TextBoxFor Extension method for datetime data:

  public static MvcHtmlString CalenderTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { Func<TModel, TProperty> deleg = expression.Compile(); var result = deleg(htmlHelper.ViewData.Model); string value = null; if (result.ToString() == DateTime.MinValue.ToString()) value = string.Empty; else value = string.Format("{0:M-dd-yyyy}", result); return htmlHelper.TextBoxFor(expression, new { @class = "datepicker text", Value = value }); } 
+2
Feb 18 2018-12-18T00:
source share

Just call him what he is looking for. How:

 Html.TextBox("Person.StartTime",Person.StartTime.ToShortDateString()); 

When it returns to the controller, your model will have limited value.

+1
Feb 15 2018-12-12T00:
source share

Have you tried to get culture to use the current application? You can override it in the web.config file with this line (in the tag):

 <!-- Default resource files are set here. The culture will also change date format, decimal, etc... --> <globalization enableClientBasedCulture="false" culture="en-US" uiCulture="en-US"/> 
0
Jan 19 '10 at 2:40
source share

A simple solution is to not use a strongly typed helper.

 <%= Html.TextBox("StartDate", string.Format("{0:d}", Model.StartDate)) %> 
0
Apr 29 '10 at 8:00
source share

I use some user assistants and have successfully used them in MVC 2 and 3 (the code is also in Snipplr ). Helpers have some kind of css logic that I use jQuery-ui datepicker in, but this can be easily removed.

 public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString, object htmlAttributes) { var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); string format = String.IsNullOrEmpty(formatString) ? "M/d/yyyy" : formatString; DateTime date = metadata.Model == null ? new DateTime() : DateTime.Parse(metadata.Model.ToString()); string value = date == new DateTime() ? String.Empty : date.ToString(format); RouteValueDictionary attributes = new RouteValueDictionary(htmlAttributes); string datePickerClass = "date-selector"; if (attributes.ContainsKey("class")) { string cssClass = attributes["class"].ToString(); attributes["class"] = cssClass.Insert(cssClass.Length, " " + datePickerClass); } else { attributes["class"] = datePickerClass; } return helper.TextBox(ExpressionHelper.GetExpressionText(expression), value, attributes); } public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression) { return DateTextBoxFor<TModel, TValue>(helper, expression, String.Empty, null); } public static MvcHtmlString DateTextBoxFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string formatString) { return DateTextBoxFor<TModel, TValue>(helper, expression, formatString, null); } 
0
Jan 18 '11 at 16:14
source share
Seriously, why should this look?

Map your base model, which has a date time object, to your mvc view model.

 //core model public class Person { public DateTime? BirthDate { get; set;} } //view model public class PersonForm { public string BirthDate { get; set; } } 

So the mapping might look like this:

 public interface IDomainToViewMapper<TModel, TViewModel> { /// <summary> /// Use an automapper or custom implementation to map domain model to presentation model. /// </summary> /// <param name="source">domain model</param> /// <returns>presentation model</returns> TViewModel MapDomainToView(TModel source); } public interface IPersonMapper : IDomainToViewMapper<Person, PersonForm> { } public class PersonMapper : IPersonMapper { #region IDomainToViewMapper<Person,PersonForm> Members public PersonForm MapDomainToView(Person source) { PersonForm p = new PersonForm(); if (source.BirthDate.HasValue) { p.BirthDate = source.BirthDate.Value.ToShortDateString(); } return p; } #endregion } 

And your controller action might look like this:

  public ActionResult Index() { Person person = //get person; var personForm = _personMapper.MapDomainToView(person); return View(personForm) } 

You no longer have to change your example.




From Chapter 2, MVC 2 in Action (Manning)

 public class CustomerSummary { public string Name { get; set; } public bool Active { get; set; } public string ServiceLevel { get; set; } public string OrderCount { get; set;} public string MostRecentOrderDate { get; set; } } 

This model is intentionally simple; It consists mainly of strings. What they represented, after all: the text on the page. The logic displaying data in this object will be direct; view will only output it. The presentation model is designed to minimize decision making in the presentation.

-one
Jan 20 2018-11-11T00:
source share

Have you tried just passing the date format you need?

 Html.TextBoxFor(model => model.BirthDate.ToString("MM/dd/yyyy"), new { style = "width: 75px;" }) 
-3
Jan 18 '10 at 18:29
source share



All Articles