0

I'm going nuts here. I'm learning web and I'm trying to get some JQuery / AJAX functions to work:

If i were to remove the line:

var wtf = @Model.CurrentMatchDB.match_id;

then it works fine. but just that line alone breaks the function and I have no idea why. I really do want to pass the model members to the match_id and row_id under data.. but that isn't working neither.

I've been on this for a couple hours now, can anyone help me out? Thanks

<script>
    $(document).ready(function () {

        $('#button_setCurrMatch').click(function (e) {
            e.preventDefault();

            var wtf = @Model.CurrentMatchDB.match_id;  //THIS LINE ERRORS

            $.ajax('/CurrentMatch/ChangeMatchTest', {
                type: 'POST',
                data: {
                    match_id: "SUPPOSED TO BE A STRING FROM the MODEL HERE",
                    row_id: "SUPPOSED TO BE AN INT FROM THE MODEL HERE"
                },
                success: function () {
                    alert('SUCCESS');
                },
                error: function (request, errorType, errorMessage) {
                    alert("Error: " + errorType + " with message: " + errorMessage);
                }
            });
        });
    });
</script>
user1189352
  • 3,628
  • 12
  • 50
  • 90
  • so what eventually happened? did any of the answers help? are you still stuck? sorry, just curious :) – AmmarCSE May 28 '15 at 22:22
  • @AmmarCSE hey jus got back to this. the double quotes did the trick for me. your links did help though as far as understanding some things. ty – user1189352 May 28 '15 at 23:15

2 Answers2

3

Try wrapping match_id in quotes

var wtf = "@Model.CurrentMatchDB.match_id";

If it's supposed to be a string it needs the quotes around it, otherwise you end up with something like

var wtf = my match id;

which is not valid syntax.

Brandon
  • 68,708
  • 30
  • 194
  • 223
  • @Brandon, I dont think this solution will work. What your doing is setting `wtf` to literally "@Model.CurrentMatchDB.match_id". This will make the error go away, but wont address the OPs goals – AmmarCSE May 28 '15 at 21:11
  • @AmmarCSE, I don't believe that is correct. The Model.CurrentMatchDB.match_id will be evaluated server side before being rendered into the markup. – Brandon May 28 '15 at 21:20
2

Mixing javascript and Razor requires that you surround your Razor call with any code block

@{ ... } or @if, etc.

and putting the code itself in an escaped sequence

@: or the <text> tag.

So, knowing this, you can do something like

    @{
        <text>
            var wtf = '@Model.CurrentMatchDB.match_id';
        </text>
     }

See Mix Razor and Javascript code and Using Razor within JavaScript

Community
  • 1
  • 1
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53