jle jle - 5 months ago 34
Ajax Question

Bootstrap Date Display Always in Wrong Format

I've got a seemingly simple date display that shows either a default "Start Date" or an AJAX result date when another "Sale Date" DropDownBoxFor is toggled. The date format should be set as short date, but the display always shows up in a date and time format. After toggling the "Sale Date" field, the "Start Date" is retrieved for the corresponding "Sale Date" and displayed as an RFC1123 date!

Model:

public DateTime StartDate { get; set; }


Razor:

@Html.TextBoxFor(m => m.StartDate, "{0:d}", new { @readonly = "readonly", @class = "form-control" })


AJAX:

success: function (data) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(data[0].StartDate);
var dt = new Date(parseFloat(results[1]));
$("#StartDate").val(dt);


After changing the TextBoxFor to a DisplayFor, the short date showed up correctly, but wouldn't update after toggling the other field. So, I wrapped the DisplayFor in a span and replaced the
.val()
change with
.html()
in the AJAX, but the formats reverted back to the incorrect date and time for default and RFC1123 after the toggle! Can anyone see what is going on here? Many thanks in advance!

jle jle
Answer

I never did find out why this is happening, but my workaround accomplishes the end goal: I changed the TextBoxFor to an EditorFor, then any time the toggle was used, the script changes the html text to the resulting date.

Razor:

<div class="startDate">
    @Html.EditorFor(m => m.StartDate, "DateTime", "StartDate", new { @class = "form-control" })
</div>

AJAX:

success: function (data) {
    var pattern = /Date\(([^)]+)\)/;
    var results = pattern.exec(data[0].StartDate);
    var dt = new Date(parseFloat(results[1]));
    $(".startDate").text((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear());