Rajitha Chamod
Rajitha Chamod

Reputation: 33

How access JavaScript variable inside c# code

Here in my ASP .NET Core MVC project I call JavaScript function with a parameter.

 <span onclick="workloadFunction(11)">Click</span>

Then in the function I wants to loop my model data and check a condition with if statement. So if statement write with c# but I cannot access the JavaScript parameter value inside the if statement.

<script>
function workloadFunction(idvalue) {
   @foreach(var project in Model.activeProjects)
   {
      @if(project.id == idvalue)
      {
          //rest of code
      }
   }
</script>

I wants to access 'idvalue' inside the if statement.

Upvotes: 1

Views: 542

Answers (1)

Amit
Amit

Reputation: 823

 <script>
    function workloadFunction(idvalue) {
     var items = @Html.Raw(Json.Encode(Model.activeProjects));
      for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (item.id == idvalue) {
             //rest of code
           }
         }
      }
 </script>

Upvotes: 4

Related Questions