TextBoxFor for Nullable type

1.5k Views Asked by At

How can i user TextBoxFor for nullable type, in my case DateTime?

<%:Html.TextBoxFor(m => m.LeaseDate.Value.ToShortDateString(), new { @class = "def-text-input datetime-input" })%>

I try this, but get error :

Exception Details: System.InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

4

There are 4 best solutions below

3
On

TextBoxFor should be used for a property on your ViewModel:

<%:Html.TextBoxFor(m => m.LeaseDate, new { @class = "def-text-input datetime-input" })%>

If you want to format your date, you can use the DataFormatString property on the DisplayFormat attribute on your ViewModel:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime LeaseDate { get; set; }
1
On

model:

[DisplayFormat(DataFormatString = "{0:MM/dd/yy}", ApplyFormatInEditMode= true]
DateTime? dateAssign { get; set; }  

view:

@Html.TextBoxFor(model => model.myObject.dateAssign)
1
On

You can use Html.EditorFor

<%:Html.EditorFor(m => m.LeaseDate, "Date")%>

Note the parameter "Date". This is a reference to an EditorTemplate (a usercontrol usualy located in the "Views/Shared/EditorTemplate" folder). If not present create the usercontrol/file your self "Date.ascx"

Now the EditorFor method will use this control as a template. A single place to control all your Date fields that use this template!

Example of the UserControl "Date.ascx"

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
    ViewDataDictionary attributes = ViewData;
    attributes.Add("class", "def-text-input datetime-input");
%>
<%= Html.TextBox(string.Empty, string.Format("{0:d-M-yyyy}", Model), attributes) %>
0
On

As the other guys mentioned you could do formatting on the model

[DisplayFormat(DataFormatString = "{0:MM/dd/yy}", ApplyFormatInEditMode = true)]
public DateTime LeaseDate { get; set; }

and then call

@Html.TextBoxFor(x => x.LeaseDate)

on your view

But on the other hand, if you want to stick with formatting on view, you can use

@Html.TextBox("LeaseDate", Model.LeaseDate.ToShortDateString())

Happy coding