简体   繁体   English

如何通过 EvaluateScriptAsync 访问 javascript 中的 c# 变量?

[英]how to access c# variable inside javascript through EvaluateScriptAsync?

I have ac# variable,我有 ac# 变量,

    double amt = 12;

and I have a Javascript piece of code我有一段 Javascript 代码

    browser1.EvaluateScriptAsync("var x='<% =amt %>';document.querySelector('.amount').value=x;");

which amends the value of the element with <%amt%>.它用 <%amt%> 修改元素的值。 What I want is to pass the actual c# variable's value '12' to be passed into.我想要的是传递要传入的实际 c# 变量的值“12”。

and when I do当我这样做时

 browser1.EvaluateScriptAsync("document.querySelector('.amount').value='12';");

it gives '12' for the value of the element.它为元素的值提供“12”。

now how do I make the element to display whatever the value the c# variable takes?现在我如何使元素显示 c# 变量采用的任何值?

I think you can use diffirent way.Generate a Label element which is sytle visible :false.我认为您可以使用不同的方式。生成一个样式可见的标签元素:false。 And you can get the element value.您可以获取元素值。

Like that :像那样:

 <asp:Label ID="lblHidden" runat="server"  Visible="false"></asp:Label>

 lblHidden.Text = "12";

and js和js

var myValue=$('#<% =lblHidden.ClientID %>').val();
browser1.EvaluateScriptAsync("var x=myValue;document.querySelector('.amount').value=x;");

 //directly insert the c# variable with "+" browser1.EvaluateScriptAsync("document.querySelector('.amount').value='"+c#variable+"';");

I figured out that the c# variable could be directly inserted like in the above code.我发现可以像上面的代码一样直接插入 c# 变量。

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

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