简体   繁体   中英

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?

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!

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM