0

I'm trying to do a simple call from html to C# to return the current 'Message' in an array. I am trying to send the index in the array from a javascript method, but it's not letting me, saying "The name 'rowID' does not exist in the current context". I understand from this Stack Overflow post, that he's struggling to pass in the variable, however for him there's no parameter to insert. So I'm still stick on the same problem. This is what I want to do:

var rowID = table.row('.selected').index();
SetSmartWindow(@Model.Messages[rowID].DeviceId, false, false, false, false, false, false);
Community
  • 1
  • 1
Nigel
  • 15
  • 6
  • JS = clientside, C# = serverside. They cannot communicate directly – Liam Aug 10 '16 at 10:37
  • That syntax is Razor. Are you using MVC/Razor? – Liam Aug 10 '16 at 10:37
  • Possible duplicate of [How do I give JavaScript variables data from ASP.NET variables?](http://stackoverflow.com/questions/553813/how-do-i-give-javascript-variables-data-from-asp-net-variables) – Liam Aug 10 '16 at 10:38

2 Answers2

0

You can use below approach to obtain the required values.

Convert the Model.Messages to a javascript array.

    var messages = JSON.parse('@Html.Raw(@Model.Messages)');
    var rowID = table.row('.selected').index();
    var deviceId = ''; 
    //write logic here to find the appropriate device id
    SetSmartWindow(deviceId, false, false, false, false, false, false);  
Mads...
  • 391
  • 2
  • 11
0

You simply cannot achieve this. Razor is compiled and rendered while on server side but javascript is compiling and working on client side. You should make an ajax request in your javascript code to get the DeviceID in your javascript code. Or you can print your array on html to assign it to a javascript variable. Like this.

@{
       string arrayStr="";
       foreach (var Message in Model.Messages)
       {
          arrayStr+=Message.DeviceID+ ",";

       }
       arrayStr=arrayStr.Substring(0, arrayStr.Length-1)
}


<script type="javascript">

var deviceIdList = [ @arrayStr ];
var rowID = table.row('.selected').index();
SetSmartWindow(deviceIdList[rowID], false, false, false, false, false, false);

</script>
Efe Özazar
  • 61
  • 1
  • 6