user2204438
user2204438

Reputation: 59

How can i use model in Javascript?

Example :

<script type="text/javascript">
        function abc() {
            var t = document.getElementById("name").value;
            @foreach(Player pl in Model){
            if (t == pl.Name) {
                alert("This name is already use!");
            }                
        }
    </script>

Error : t - cannot resolve symbol How can i use JavaScript variable in C# code? Is it possible in this example?

Upvotes: 0

Views: 181

Answers (2)

Andrey Stukalin
Andrey Stukalin

Reputation: 5919

You may do something like this.

<script type="text/javascript">
    function abc(players) {
        var t = document.getElementById("name").value;
        for(p in players) {
        if (t == p.Name) {
            alert("This name is already use!");
        }                
    }

    abc(@Html.Raw(Json.Encode( Model )));
</script>

Upvotes: 0

Nikola Sivkov
Nikola Sivkov

Reputation: 2852

You cannot use JS variables in C# code , but you can use C# variables in the code. In most cases C# is used to render HTML or JS.

In your case it would be best if you render your C# serverside model as a JS array , which you can later on iterate.

  1. make an action that returns your list (assuming it's a list) as a JSON

  2. fetch the data with an AJAX get call to your action.

Cheers!

Upvotes: 2

Related Questions