Home > OS >  How to make javascript variables unique inside an asp.net core foreach?
How to make javascript variables unique inside an asp.net core foreach?

Time:09-02

I've something like the following in a razor page:

@foreach (var item in list)
        {
            <h3 id="[email protected]"></h3> <!--The id is unique because of the addition of the list item's ID-->
        <script type="text/javascript">
                let [email protected] = new Date(Date.now());
                $('#[email protected]').html([email protected]) // Item.id displays like text and doesn't apply to the variable itself.
                function [email protected](){ // Functions too
                }
            </script>
        }

I need to make those variables/function/IDs unique for each item of the list.

CodePudding user response:

Wrap item.id in parentheses: @(item.id)

@foreach (var item in list)
{
    <h3 id="[email protected]"></h3>
    <script type="text/javascript">
        let currentDateTime-@(item.id) = new Date(Date.now());
        $('#time-@(item.id)').html(currentDateTime-@(item.id));
        function getdone-@(item.id)(){
        }
    </script>
}

Result:

descr

https://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/

  • Related