-1

I have some troubles with JavaScript. How to use JavaScript in razor @foreach section? So, I'm trying to take some data from a model and put that data into HTML table. I need an access to variables, which were set in @foreach section (variables with caps lock). Could somebody help me?

<script type="text/javascript">
    function AddClick() {

    @foreach (var x in Model) {
        var FIRSTNAME= @x.Name;
        var LASTNAME= @x.Surname;
        var SUBJECT1= @x.Physics;
        var SUBJECT2= @x.Math;

        <text>
        var table = document.getElementById("regtable");
        var row = table.insertRow();

        var zero = row.insertCell();
        var FirstnameCell = row.insertCell(1);
        var LastnameCell = row.insertCell(2);
        var PhysCell = row.insertCell(3);
        var MathCell = row.insertCell(4);

        FirstnameCell.innerHTML = FIRSTNAME ;
        LastnameCell.innerHTML = LASTNAME;
        PhysCell.innerHTML = SUBJECT1;
        MathCell.innerHTML = SUBJECT2;

        </text>

        }

}

Tony Hinkle
  • 4,706
  • 7
  • 23
  • 35
  • 1
    check this one. http://stackoverflow.com/questions/5614941/mix-razor-and-javascript-code – Deep Jun 14 '16 at 15:05
  • 2
    Specifically how is this failing? What client-side code does this generate? Defining the problem is always the first step toward solving it. – David Jun 14 '16 at 15:07

1 Answers1

1

You can't really mix Razor and JavaScript like this. Razor runs on the server side, and JavaScript runs on the client side. When the Razor is generating HTML on the server side, JavaScript is not available to you, and by the time the JavaScript is running on the client side, any Razor code is over and done with.

What you can do is use Razor to dump your model data into a JavaScript variable and then have your have your script use that once it's on the client side. Check the link provided by @Deep in the comments to see one example of how to do this.

jmoerdyk
  • 5,544
  • 7
  • 38
  • 49