Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass List<int> from Model to jQuery int[]

I would like to pass a list of integers from my Model to jQuery. But, I am unsure of the jQuery syntax. Any help on how to fill the window.checkedCoursesArray values would be appreciated.

Model:

public List<int> PrintCourses { get; set; }

Controller:

var listCourseIDs = (from c in listFilteredTREs
                             select c.CourseID).ToList();
homeViewModel.PrintCourses = listCourseIDs;

JQuery:

window.checkedCoursesArray = new Array();

Thanks for all the help. Here is the finished jQuery/Razor code:

@foreach(var item in Model.PrintCourses)
{
    @:window.checkedCoursesArray.push(@item);
}
like image 387
ADH Avatar asked Dec 31 '25 04:12

ADH


1 Answers

//controller:

[HttpGet]
public JsonResult PrintCourses()
{
    var listCourseIDs = new List<int>() { 1,2,3,4,5};

    return Json(listCourseIDs, JsonRequestBehavior.AllowGet);
}

//view:

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            var url = '@Url.Action("PrintCourses")';
            $.get(url, function(data) {
                for (i = 0; i < data.length; i++) {
                    alert(i);
                }
            });
        });

    </script>

====================================================================

//Controller

public ActionResult Index()
{
    var model = new PrintCourses();
    model.ids = new List<int>() {1, 2, 3, 4, 5};

    return View(model);
}

//View

@model MvcApplication6.Models.PrintCourses
@foreach (var id in Model.ids)
{
    @id<br/>
}
like image 88
Thiago Custodio Avatar answered Jan 02 '26 22:01

Thiago Custodio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!