Templates can be used only with field access… error using ToShortDateString()

While binding a partial view to a model, I noticed the my nullable DateTime field was showing the time portion. Adding attributes to the model didn’t work, so I attempted to use the ToShortDateString() method:

@Html.TextBoxFor(model => Model.StartDate.Value.ToShortDateString(), new { @class = “form-control”, @maxlength = “10” })

However, this caused the error “Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions”.

To get around this, set the shortened date value to a string, and used that as the binding to the textbox:

var startDate = Model.StartDate.Value.ToShortDateString();

@Html.TextBoxFor(model => startDate, new { @class = “form-control”, @maxlength = “10” })

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: