简体   繁体   English

在 JavaScript function 被调用时执行 C# 代码

[英]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:每当我运行 JavaScript function 时,我都想执行一段 C# 代码,但它的行为似乎不像我想要的那样,这是一个例子:
Let's say that I have a variable property int Counter {get; set; }假设我有一个变量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:property int Counter {get; set; }中,我想在每次运行 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.真正发生的是,当页面加载时@{Model.Counter++;}正在执行,无论是否从 function 调用。
And whenever I run the function again its ignoring it completely.每当我再次运行 function 时,它都会完全忽略它。
Meaning this piece of code @{Model.Counter++;} is getting executed once when the page loads and never again.这意味着这段代码@{Model.Counter++;}在页面加载时执行一次,并且不再执行。
How do I fix that and make it execute every time I run the function?每次运行 function 时,如何解决并使其执行?

I don't think what you want is possible (maybe with Blazor? - but that is WebAssembly).我不认为你想要什么是可能的(也许是 Blazor? - 但那是 WebAssembly)。 Instead you can assign a new javascript variable to your model property.相反,您可以将新的 javascript 变量分配给您的 model 属性。 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.您可以使用 ActiveX 控件来执行编译程序。 but you should know that your html code only will work in IE.但您应该知道您的 html 代码仅适用于 IE。

You will have to create a hidden field for model.counter somewhere inside a view form您必须在视图表单内的某处为 model.counter 创建一个隐藏字段

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

after this you can change Counter using javascript在此之后,您可以使用 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并在 function 或脚本中执行

@a++;

or或者

 var c = @a;
    c++;

hope it works希望它有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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