0

I am using html.textbox for 2 of my datetime field because I need to format them in a specific format but i don't know how to do it by html.textboxfor. However, I realise i need to have the textboxfor for the validation in my model class to work:

  [Required(ErrorMessage = "Storage Date is required")]
  [DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
  public DateTime StorageDate { get; set; }

Any idea how can I change my Html.Textbox below into Html.TextBoxFor with the same setting??

  @Html.TextBox("expirydate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "expirydate" })
    @Html.ValidationMessageFor(model => model.ExpiryDate)

Appreciate any help... Thanks...

1 Answer 1

1

You don't really need to use TextBoxFor() for validation to work. If your TextBox has the same id as a field in the model, the model binder will pick it up. If you're talking about to get the unobtrusive validation features, you can always manually add the data-* attributes to your TextBox.

However, in this case it sounds like what you really want is a custom editor, using EditorFor(). It's a bit more work, but it will allow you to actually enforce the date/time formatting by giving the user something like a date/time picker control. The basic idea is:

  • Create a partial view called DateTime.cshtml that is bound to model of type Nullable<DateTime>, and put it into the Shared/EditorTemplates view folder.
  • Use jQuery and jQueryUI to put an HTML textbox that is styled as a date/time picker into the partial view.
  • Decorate the property on your model with the [DataType(DataType.DateTime)] attribute
  • Use Html.EditorFor(model => model.WhateverProperty)

Fortunately, date/time pickers are probably the most popular custom MVC3 editor, so there are plenty of examples to pick from; the code from this question works fine, just make sure to note the suggestion in the answer and replace this line in the partial view:

@inherits System.Web.Mvc.WebViewPage<System.DateTime>

with this:

@model System.DateTime?
Sign up to request clarification or add additional context in comments.

1 Comment

HI, thanks a lot but actually i used editorfor previously. However, I need to do some different setting on each of the datetime field datepicker, so i separate it with different id. Btw, I also noticed I do not really need the textboxfor for validation to work!

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.