Mathias Andersson
Mathias Andersson

Reputation: 105

How to increment and use a value in Jquery and Razor pages, in ASP.net core 2.0

I have this script here, but i need to either be able to use Jquerys ival, or be able to increment the model pages ival from the jquery loop. Think a typcal c# for loop.

The different examples:

    $(document).ready(function() {
    $("button").click(function () {
        $(".divs").each(function (index, element) {

            var ival = 0;
            $(element).css({
                top: @Model.Positions.GetValue(ival, 0),
                left: @Model.Positions.GetValue(ival, 1)
            });

        });
    });
});

(ival isnt recognized since they are technically in different scopes, one in model and one in jquery)

And:

    $(document).ready(function() {
    $("button").click(function () {
        $(".divs").each(function (index, element) {

            @{
                int ival = 0;
            }
            $(element).css({
                top: @Model.Positions.GetValue(ival, 0),
                left: @Model.Positions.GetValue(ival, 1)
            });
            @{
                ival++;
            }
        });
    });
});

(Thought that would work but it doesnt ^)

Upvotes: 1

Views: 810

Answers (1)

pitaridis
pitaridis

Reputation: 2983

I will try to reproduce your problem with two different solutions. I assume you have a class which will be used in order to store your values:

public class Position
{
    public int top { get; set; }
    public int left { get; set; }
}

You will have a property in your PageModel which will store a list of Positions and you will load a list of values to this list

public class TestModel : PageModel
{
    public List<Position> Positions { get; set; }

    public void OnGet()
    {
        Positions = new List<Position>
        {
            new Position {left = 10, top = 20},
            new Position {left = 20, top = 30},
            new Position {left = 30, top = 40},
        };
    }
}

Now you have two options. The first option is to generate your dives with C# code and the second is to generate a json object which will be used with javascript.

First Solution

@foreach (var item in Model.Positions)
{
    <div style="left: @(item.top)px; top: @(item.top)px">
        contents of your div
    </div>
}

Second Solution

<script type="text/javascript">
    var data = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Positions));
</script>

This will generate the following code in your razor page:

<script type="text/javascript">
    var data = [{"top":20,"left":10},{"top":30,"left":20},{"top":40,"left":30}];
</script>

Now you can use the data object in order to set the top and left using javascript.

I hope it helps.

Upvotes: 1

Related Questions