mdixon18
mdixon18

Reputation: 1219

ASP MVC send an Array object to a JavaScript function

I am using ASP MVC for my university coursework. However I have encountered a problem, before I was sending too many AJAX requests which was causing my page to take way too long to load. Therefore I thought I could improve the situation by sending the arrays from the database to the view and then put them into my jquery function inline.

So here is how it looks I have my simple model:

public class NewBooking
    {
        public IEnumerable<dynamic> parks { get; set; }
    }

Then in my controller I set the parks with information from the database as you can see here:

public ActionResult Index()
        {
            var model = new NewBooking();

            var parks = Database.Open("SQLServerConnectionString").Query("SELECT * FROM Park");

            var output = from o in parks
                         select new { parkID = o.parkID, parkName = o.parkName };
            model.parks = output.ToList();

            return View(model);
        }

Now, this returns to the view all the information I am expecting, as you can see below if I simply called the model parks in the view:

@model build_01.Models.Timetabler.NewBooking
@{
    @Model.parks
}

I know this method wouldn't however with a for loop it works fine, now to my issue; I'm trying to call a JavaScript function and pass this array to it.

$(document.ready(function () {
        slotAvailability(@Model.parks);
    }));

Is there something I can do to this @Model.parks to be able to send it to the function? Kind of like how I would do JSON if I was using AJAX.

As it stands trying to call it like this gives me this error in my console:

Uncaught SyntaxError: Unexpected number

I can see why, if I was to inspect element I can see that the function parse looks like this:

slotAvailability(System.Collections.Generic.List`1[&lt;&gt;f__AnonymousType3`2[System.Object,System.Object]]);

Thanks

Upvotes: 1

Views: 818

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039548

You should use the Json.Encode function. Also make sure tha you close your parenthesis at the proper place, after document:

$(document).ready(function () {
    var parks = @Html.Raw(Json.Encode(Model.parks));
    slotAvailability(parks);
});

Also using dynamic seems like a bad design here. You don't get any Intellisense. You'd rather have a view model:

public class ParkViewModel
{
    public int ParkId { get; set; }
    public int ParkName { get; set; }
}

and then your NewBooking model:

public class NewBooking
{
    public IEnumerable<ParkViewModel> Parks { get; set; }
}

Upvotes: 2

Related Questions