Ok All Weird one here ....
I have a view with a dropdown list containing 4 days prior and todays date...
When Index(Action) is lauched with a null for DateTime the DropDownList appears with the current date already selected... Great!
HTML SOURCE URL \Controller\Index
<select class="form-control" id="Date" name="Date" onchange="Change_Date(this)"
<option value="23/10/2017">23/10/2017</option>
<option value="24/10/2017">24/10/2017</option>
<option value="25/10/2017">25/10/2017</option>
<option value="26/10/2017">26/10/2017</option>
<option selected="selected" value="27/10/2017">27/10/2017</option>
</select>
When Index(Action) is launched with a DateTime, even though it goes through the exact same process and I can physically see the Selected=True property in the ViewBag.DateList... the dropdown has no selected option and reverts to the first.
HTML SOURCE URL \Controller\Index?date=2017-10-26
<select class="form-control" id="Date" name="Date" onchange="Change_Date(this)"
<option value="23/10/2017">23/10/2017</option>
<option value="24/10/2017">24/10/2017</option>
<option value="25/10/2017">25/10/2017</option>
<option value="26/10/2017">26/10/2017</option>
<option value="27/10/2017">27/10/2017</option>
</select>
I have tried bypassing the JS and putting the datetime directly in the URL but no luck so its not that...
I cannot understand why having ?date=date in the URL removes the selected property from the options elements...
Just to be Clear in both instances the Selected = True Property is present within the ViewBag.DateList, but it doesn't render as expected when a parameter is passed into the action.
View
@Html.DropDownList("Date", (IEnumerable<SelectListItem>)ViewBag.DateList,
new { @class = "form-control", @onchange="Change_Date(this)" })
Method
public ActionResult Index(DateTime? date)
{
if (date.HasValue == false)
{
date = DateTime.Now.Date;
}
List<SelectListItem> Dates = new List<SelectListItem>();
for (int i = -4; i < 1; i++)
{
string date_display = DateTime.Now.Date.AddDays(i).ToShortDateString();
Dates.Add(new SelectListItem { Text = date_display, Value =date_display});
}
foreach (SelectListItem item in Dates)
{
if (item.Value == date.ToShortDateString())
item.Selected = true;
}
ViewBag.DateList = Dates;
}
JS
function Change_Date(val)
{
var value = $('#Date').val();
value = value.split("/").reverse().join("-");
var url = "/Controller/Index?date=" + value;
window.location.href = url;
}