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>
2
  • so what eventually happened? did any of the answers help? are you still stuck? sorry, just curious :)
    – AmmarCSE
    May 28, 2015 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 May 28, 2015 at 23:15

2 Answers 2

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.

2
  • @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, 2015 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, 2015 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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.