Search code examples
c#jqueryrazorasp.net-core-mvc

can I iterate on collection coming from controller to view in section script and get data of it in ASP.NET Core MVC


    @model MVCTEST.Controllers.ViewModel 
    var id = 2;
<div id="timezone">
    <a id="url">URL</a>
</div>
    $(document).ready(function () {
        localStorage.setItem('timezone', 'cairo');
        var timezone = window.localStorage.getItem('timezone');

        // I need to iterate on collection (Model.IDs) in model which incoming from controller
        // and append every id to url, how can I do it?

        $('#url').attr('href', '../../Info/GetInfoDetails/@id?timezone=' + timezone);
    });

This code works fine, but when I try to iterate on collection I can't append every id in collection and append it to the url


Solution

  • If you'd like to pass data from controller to view through ViewModel, and then access the data in JavaScript function, you can try to modify the code like below.

    pass data from controller to view

    var vm = new ViewModel
    {
        IDs = new List<int> { 10, 12, 15 }
    };
    return View(vm);
    

    store data in a hidden field in view page

    <input id="hf_ids" type="hidden" value="@String.Join(",",Model.IDs)" />
    

    access data in js function

    @section Scripts{
        <script>
            $(document).ready(function () {
                localStorage.setItem('timezone', 'cairo');
                var timezone = window.localStorage.getItem('timezone');
    
                //access ids stored in hidden field
                var ids = $("#hf_ids").val().split(',');
                console.log("ids: ", ids);
    
                //generate url based on above ids
        });
        </script>
    }
    

    enter image description here