OBL
OBL

Reputation: 1357

MVC: Need to pass an list or array of strings from controller to view

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.

Upvotes: 3

Views: 1660

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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>

Upvotes: 4

Related Questions