JavaScript中的参考C#变量 [英] Reference C# Variable in JavaScript
问题描述
我已经阅读了很多线程,但是我无法弄清楚为什么这行不通.我正在创建一个SharePoint Web部件,它将用作导航栏.一切正常,直到我尝试在JS代码中引用C#变量为止.
I have read quite a few threads but I cannot figure out why this will not work. I am creating a SharePoint Web Part that will serve as a navigation bar. Everything works great until I try and reference a C# Variable in the JS Code.
这是VisualWebPart1UserControl.ascx.cs中的C#:
Here is my C# from the VisualWebPart1UserControl.ascx.cs:
public class myClass
{
public string theValue = "hi";
}
这是VisualWebPart1UserControl.ascx页面上的HTML/JS:
Here is the HTML/JS from the VisualWebPart1UserControl.ascx Page:
<script type="text/javascript">
function getMyValue() {
var myVar = "<%= myClass.theValue %>";
alert(myVar);
}
<li><a href="http://maindt"
onmouseover="getMyValue(), mopen('m1')"
onmouseout="mclosetime()">MAINDT Home</a>
<div id="m1"
onmouseover="mcancelclosetime()"
onmouseout="mclosetime()">
<a href="">Site 1</a>
<a href="">Site 2</a>
<a href="">Site 3</a>
</div>
</li>
发生的事情是,当我将鼠标悬停在"MaindDT Home"下拉菜单上时,我得到了很好的警报(myVar),但是当我期望它的内容是<%= myClass.theValue%>显示theValue的值为"Hi"
What happens is when I hover my mouse over the "MaindDT Home" drop down, I get the alert(myVar) which is good but the content is <%=myClass.theValue%> when I'm expecting it to display the value of theValue which is "Hi"
推荐答案
问题是-如果您尝试在单独的js文件中存储/访问变量,则根本无法实现;aspx解析器未在js/css文件上运行.
The thing is - if you try to store/access your variable in a separate js file - you simply can't; the aspx parser isn't running over js/css files.
这是我的处理方式:
您单独的javascript文件应如下所示:
Your separate javascript file should look like this:
// added a few parameters (id should be something like 'm1')
function getMyValue(id, value)
{
alert(value);
}
您的ascx文件应包含以下内容:
And your ascx file should contain this:
<!-- add a reference to the js file -->
<script type="text/javascript" src="myJavascriptFile.js"></script>
<%
// in order for this to work:
// it requires a field/property of type myClass within your page or theValue should be a static property/field of myClass
// create an instance of myClass (or get it another way...)
var myClassInstance = new myClass();
// create a simple reference to the value you want (not required - but makes it a bit more readable)
var myValue = myClassInstance.theValue;
// I'm injecting myValue as a parameter for the javascript function (this gets printed as a string - so make sure you encode it properly)
%>
<li><a href="http://maindt"
onmouseover="getMyValue('m1', '<%: myValue %>'); mopen('m1');"
onmouseout="mclosetime()">MAINDT Home</a>
<div id="m1"
onmouseover="mcancelclosetime()"
onmouseout="mclosetime()">
<a href="">Site 1</a>
<a href="">Site 2</a>
<a href="">Site 3</a>
</div>
</li>
有点晚了,但是我希望这会有所帮助!
A bit late, but I hope this helps!
这篇关于JavaScript中的参考C#变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!