3

I need to populate an object in the script section of my mvc page, currently the object looks like this:

<script>
var disabledDays = ["9-30-2011","2-24-2010","2-27-2010","2-28-2010","3-3-2010","3-17-2010","4-2-2010","4-3-2010","4-4-2010","4-5-2010"];

Now I am trying to pass an array of DateTime objects to the view from the controller, but converting it to strings before I do that. Something like this:

<Controller>
var blockedDates = new List<string>();
            foreach (DateTime closeDate in dealershipInfo.ClosedDates)
                blockedDates.Add(closeDate.ToString());
            ViewBag.BlockedDates = blockedDates;

But definitely it is not working for me. What will be the proper way to achieve this kind of a result.

1 Answer 1

4
public ActionResult Index()
{
    var blockedDates = dealershipInfo.ClosedDates.Select(x => x.ToString()).ToList();
    return View(blockedDates);
}

and in the view:

@model IEnumerable<string>
...
<script type="text/javascript">
    var disabledDays = @Html.Raw(Json.Encode(Model));
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Where do I need to add this line? @model IEnumerable<string> I tired it and it is throwing an error, tag sting is not closed. Also thank you so much for all the help. :)

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.