Reputation: 269
In a view, there's a DisplayFor tied to a DateTime field in the Model. To update the field, an AJAX call returns a Date. I can convert the AJAX date into a MM/DD/YYYY value, but setting the DisplayFor with a .val doesn't update the view. Chrome Developer Tools shows no error, and in fact shows the correct converted DateTime, but the DisplayFor doesn't update. I haven't tried changing the .attr instead of the .val because it seems like .val would be the correct option. Can anyone see why the view isn't updating? Thanks in advance!
Model declaration:
DateTime? SaleDate { get; set; }
DisplayFor in View:
@Html.LabelFor(m => m.SaleDate, "Sale Date")
@Html.DisplayFor(m => m.SaleDate, "{0:d}", new { @class = "form-control" })
Update script inside successful AJAX call:
success: function (data) {
var $sDate = $("#SaleDate");
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(data[0].SaleDate);
var dt = new Date(parseFloat(results[1]));
$sDate.val(dt); //dt is correct Date, but DisplayFor isn't updating!
}
EDIT
The page source indicates that the id is correct, but there's no input. I assume this is because of a DisplayFor vs. a TextBoxFor, but could the apparent absence of an id be the problem?
<label for="SaleDate">Sale Date</label>
6/1/2016 12:00:00 AM//no input section, just the DateTime value
Or, if SaleDate is null:
<label for="SaleDate">Sale Date</label>
//no value or input section
Upvotes: 0
Views: 412
Reputation: 9470
The Razor code in the View produces some HTML code. Javascript works on client side and has no idea about Razor's @Html.DisplayFor
, only about its output. I'm not strong in Razor so my offer can contain errors.
1. @Html.TextBoxFor(m => m.SaleDate, "{0:d}", new { @class = "form-control", id = "SaleDate" })
.
JS remains the same. Con: This is editable textbox (input)
2. <span id="SaleDate" class="form-control">@Html.DisplayFor(m => m.SaleDate, "{0:d}")</span>
JS last line should be $sDate.html(dt);
I hope it helps.
Upvotes: 1