Animus Miles-Militis Animus Miles-Militis - 1 year ago 96
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)

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));

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:


Opposed to resulting the following when I use the json:


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 Source

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)
return View(vm);

Now in the razor view,

@model YourViewModel
   var availableDates = @Html.Raw(Newtonsoft.JsonJsonConvert
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download