简体   繁体   中英

Execute C# code inside JavaScript function when it's called

I want to execute a piece of C# code whenever I run a JavaScript function but it doesn't seem to behave the way I want it to here is an example:
Let's say that I have a variable property int Counter {get; set; } property int Counter {get; set; } property int Counter {get; set; } in the Model that I want to increment every time I run a JavaScript function:

<script type="text/javascript">

function MyFunction(){

    //Do some stuff
    @{Model.Counter++;}

}

</script>

What is really happening is that when the page loads @{Model.Counter++;} is getting executed regardless of not being called from the function.
And whenever I run the function again its ignoring it completely.
Meaning this piece of code @{Model.Counter++;} is getting executed once when the page loads and never again.
How do I fix that and make it execute every time I run the function?

I don't think what you want is possible (maybe with Blazor? - but that is WebAssembly). Instead you can assign a new javascript variable to your model property. Eg:

<script type="text/javascript">

function MyFunction(){

    //Do some stuff
    let counter = @{Model.Counter};
    counter++;

    // Do some stuff with counter

}
// When you are done, post the counter back if needed on server side

</script>

You can use ActiveX control to execute Compiled program. but you should know that your html code only will work in IE.

You will have to create a hidden field for model.counter somewhere inside a view form

<input type="hidden" id="modelCounter" asp-for="Counter" value="@Model.Counter" />

after this you can change Counter using javascript

function MyFunction(){

    //Do some stuff

var counter=$("#modelCounter").val();
counter++;
   $("#modelCounter").val(counter);

}

Try This

     @{
   var a=Model.Counter;
     }

do this outside the script

and inside the function or script do

@a++;

or

 var c = @a;
    c++;

hope it works

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