Animus Miles-Militis Animus Miles-Militis - 29 days ago 12
jQuery Question

Jquery datepicker - Pass date array from Controller MVC

I have created a List containing available dates and serialized it into json:

List<string> dates = new List<string>();

foreach(BookingDates itm in model.availableDates)
{
dates.Add(itm.expDate.ToString("dd-MM-yyyy"));
}

model.datesStr = new JavaScriptSerializer().Serialize(dates);


I then pass model data to jquery and try to pass the dates to the datepicker:

var availableDates = @Html.Raw(Json.Encode(@Model.datesStr));
alert(availableDates);

function available(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, availableDates) != -1) {
return [true, "ui-available", "Available"];
}
else {
return [false, "ui-unavailable", "unAvailable"];
}
}


The datepicker does not populate with dates.
If however I type the dates, it does:

var availableDates = ["20-11-2016","17-12-2016"];


The only difference I have noticed is the result of my alert when dates typed as above is:

20-11-2016,17-12-2016

Opposed to resulting the following when I use the json:

["20-11-2016","17-12-2016"]

I have also tried declaring the var as an array:

var availableDates = [];
availableDates = @Html.Raw(Json.Encode(@Model.datesStr));


again with no success implementing the json. SHould I be in some way converting my json to string separated with comma?

Answer

JavaScriptSerializer().Serialize method will convert your list to a string. If you want a javascript array for your client side code, you should change the view model property from string to a collection (array/list).

public class YourViewModel
{
  public List<string> Dates { set;get;}
  //Other properties 
}

And in your action method,

foreach(BookingDates itm in model.availableDates)
{
    vm.Dates.Add(itm.expDate.ToString("dd-MM-yyyy"));
}
return View(vm);

Now in the razor view,

@model YourViewModel
<script>
   var availableDates = @Html.Raw(Newtonsoft.JsonJsonConvert
                                            .SerializeObject(Model.Dates))
   console.log(availableDates);
</script>