user1859269
user1859269

Reputation:

How can i write JavaScript between server side code in razor view?

Eg.

 $(".button").click(function () {
                var index=$(this).closest('tr').index();
                var [email protected][index];               
            });

In this,index is javascript and @Model.Task is server side so error say "The name index does not exist in the current context".

Upvotes: 0

Views: 81

Answers (2)

Misiakw
Misiakw

Reputation: 922

as it was told by vivek and Andrei - it is impossible. index is variable from javascript, and Model.Task is array from model. they are executed in different moment. think about it that way. All values obtained from Model are executed/parsed by server before sending response to client (browser). it means that client sees them as normal text, not as an object. But javascript is executed on client (browser) AFTER page was downloaded and rendered (and the code you provided is executed even later - after button was clicked). This means that when Model is parsed it has "no idea" about javascript.

the only way to do what you want to do is what KnowGe posted - save all Model.Task table as javascript object and then use this object in your listener

Upvotes: 0

KnowGe
KnowGe

Reputation: 305

Before on click function, you should do below.

var tasks = JSON.parse('@Html.Raw(Model.Task)');

After then you can do

$(".button").click(function () {
            var index=$(this).closest('tr').index();
            var records = tasks[index];               
        });

Upvotes: 2

Related Questions