1

Working with MVC 4 & I created a Editor template to show only the time in HH:mm format from DateTime object

Editor Template Code (TimePicker.cshtml)

@model DateTime?
@{
    String modelValue = "";
    var dateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat;
    var id = "";
    var cls = "";
    var style = "";
    var placeholder = "";

    if (ViewData["_id"] != null)
    {
        id = (string)ViewData["_id"];
    }
    if (ViewData["_class"] != null)
    {
        cls = (string)ViewData["_class"];
    }
    if (ViewData["_style"] != null)
    {
        style = (string)ViewData["_style"];
    }
    if (ViewData["_placeholder"] != null)
    {
        placeholder = (string)ViewData["_placeholder"];
    }

    if (Model.HasValue)
    {
        if (Model.Value != DateTime.MinValue)
        {
            modelValue = Model.Value.ToString("HH:mm", dateFormat);
        }
    }
}
@Html.TextBox("", modelValue, 
           new { @class = cls, @id = id, @style = style, @placeholder = placeholder })

In View

 @Html.EditorFor(m => m.StartTime, "TimePicker", new { _id = "StartTime"})

But the Final HTML Rendered was

 <input id="StartTime" name="StartTime" type="text" value="2013-08-05 0:00:00" />

Even I tried hard coding the value for debugging like below

@Html.TextBox("", "00:00", 
           new { @class = cls, @id = id, @style = style, @placeholder = placeholder })

Still I get same 2013-08-05 0:00:00 instead of 0:00

What is the problem in the code?

EDIT: In Quick watch adding name parameter to TextBox gives a result. But it appends it with name attribute, which i dont want. Find this screenshot enter image description here

Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120

1 Answers1

3

After reading this MVC 3 - Html.EditorFor seems to cache old values after $.ajax call , I realized that before binding, HtmlHelper will look into ModelState.

Not sure what is the intention/benefit of checking the ModelState, instead of binding what ever the value supplied.

However I added this code in my controller before setting the value. Now it works fine.

 ModelState.Remove("StartTime"); 
 ModelState.Remove("EndTime");

 bookingViewModel.StartTime = Convert.ToDateTime(startTime);
 bookingViewModel.EndTime = Convert.ToDateTime(endTime);

 return View("Booking", bookingViewModel);
Community
  • 1
  • 1
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120