user1189352
user1189352

Reputation: 3885

Can't grab ASP.NET/MVC "Model" members into my JQuery function

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>

Upvotes: 0

Views: 53

Answers (2)

Brandon
Brandon

Reputation: 70022

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.

Upvotes: 3

AmmarCSE
AmmarCSE

Reputation: 30607

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

Upvotes: 2

Related Questions