views:

98

answers:

2

Is it possible to format inline with String.Format inside edit forms where you use lambda expression with TextBoxFor HTML helpers?

Something like this but this obviously fails but hopefully you will get what I mean

<%: Html.TextBoxFor(String.Format("{0:d}", model => model.IssueDate), new { @class= "invoiceDate"}) %>
A: 

Html.TextBoxFor needs a delegate, but you are passing it the result of calling String.Format when String.Format is passed a delegate.

You need to put the call to String.Format (or, simpler, ToString) inside the delegate:

<%: Html.TextBoxFor(model => model.IssueDate.ToString("d"), new { @class= "invoiceDate"}) %>

But as you note in your comment:

Gives this exception "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."

This is because Html.TextBoxFor is expecting an Expression<T> and decoding that to extract which property/method/field you are accessing. It will then use this information to later directly access the member.

You can either use Html.TextBox, or add a property to your model type which includes the formatting.

Richard
Using Html.TextBox would force me to go back using non strongly typed helpers, which I don't want. Using formatted property also wouldn't work because data is saved into DB as datetime and we want it that way.
mare
I've found a solution with custom html helper extensions but I have a problem which I discuss in the revised question.
mare
Re. the first comment: a formatted property would be read only, used for output. This would only be about presentation of the data to consumers (who read it as text).
Richard
A: 

Apparently I completely missed on EditorFor helpers (and there are DisplayFor helpers also, going along the same lines as EditorFor ones).

You can access the model using strongly typed EditorFor helper like this:

<%: Html.EditorFor(model => model.ServiceDate) %>

Then in Views/Shared/ folder create a subfolder called EditorTemplates and create a DateTime.ascx in it with this contents:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %>
<%: Html.TextBox("", Model.ToShortDateString(), new { @class= "editDate"}) %>

This then allows us to have strongly typed helpers but also use formatting for the properties types.

mare