1

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?

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.