0

i am unable to solve problem from last two days.

@Html.TextBoxFor(model => model.myObject.dateAssign, String.Format("{0:MM/dd/yy}"))

here, dateAssign is nullable datetime. it may be or maybe not have value.

i am keep getting following error

Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

please give me some hint or direction

1
  • "" is not date, ?? will throw error, as DateTime is valuetype and string is reference type Commented Nov 8, 2013 at 7:00

1 Answer 1

4

String.Format() needs a second argument (see documentation) - in your case your date.

Have a look at this page for date formats.

Then you would write something like

@Html.TextBox(model => String.Format("{0:MM/dd/yy}", model.myObject.dateAssign))  

Or, if you want to use @Html.TextBoxFor, you can annotate your property like this:

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

// and in your view:
@Html.TextBoxFor(model => model.myObject.dateAssign)
Sign up to request clarification or add additional context in comments.

4 Comments

here date is nullable
i tried but that changes the error to "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions."
String.Format works with null, too. It's just empty, then. To your second question: Replace @Html.TextBoxFor with @Html.TextBox. That should work.
The [DisplayFormat] attribute is only used in EditorFor/DisplayFor, and not by the raw HTML APIs like TextBoxFor and also DisplayFormat works when we set ApplyFormatInEditMode= true in dataanotations

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.