2010-10-13 48 views
0

我想知道如何在JavaScript中使用C#变量?在javascript中使用c#变量

+4

请解释[读的C#属性为jQuery代码]更好 – 2010-10-13 07:41:35

+2

可能重复(http://stackoverflow.com/questions/1300128/reading -c-property-into-jquery-code) – 2010-10-13 07:47:25

回答

6

如果我理解你的意图,在你的ASPX页面试试这个

<script type="text/javascript"> 
<!-- 
function showCSharpVar() { 
    alert('<%= myCSharpVariable %>'); 
} 
--> 
</script> 

其中myCSharpVariable在声明公共变量的代码隐藏这样

public string myCSharpVariable = "display me"; 

你也可以做一个网页如果您需要完成更多的工作,可以在页面上找到公共财产。

另一种选择是使用RegisterClientScriptBlock()或RegisterStartupScript()将脚本直接嵌入到页面中。这些是我用来决定哪种情况最好的标准。

//A. 
// Page.RegisterClientScriptBlock() will insert the *block* of script just after <form>. 
// Page.RegisterStartupScript() will insert the script at end of <form>. 
//B. 
// Page.RegisterClientScriptBlock() should usually be used for scripts encapsulated in functions. (hence the word "block") 
// Page.RegisterStartupScript() can be used for any script, even if it's not in a function. 
//C. 
// Page.RegisterClientScriptBlock() should be used for functions that don't need to run on Page load. 
// Page.RegisterStartupScript() should be used for scripts that must run on Page Load. 
//D. 
// Page.RegisterClientScriptBlock() should be used for a script that does not require the form elements to have been created. 
// Page.RegisterStartupScript() should be used for scripts that require the form elements to have been created and uses references to them. 
// 

使用这种方法,你可以注入的JavaScript到页面(例如,您在留言询问了数组),但它使经常难以追踪的错误,你将不能够单元测试。

如果您使用的是UpdatePanels,则可能需要使用其中一个或另一个,具体取决于它是全部还是部分回发。试试这个来解决这个问题

if (ScriptManager.GetCurrent(referenceControl.Page).IsInAsyncPostBack) 
{ 

    ScriptManager.RegisterClientScriptBlock(referenceControl, referenceControl.GetType(), "uniqueID", 
     "Your Script Here", true); 
} 
else 
{ 
    ScriptManager.RegisterStartupScript(referenceControl, referenceControl.GetType(), "uniqueID", 
     "Your Script Here", true); 
} 
+0

这是不是也要求页面本身是绑定到类实例后面的代码的数据? – Justin 2010-10-13 07:57:15

+0

好的非常感谢,但另外1个问题是为变量,但我怎么可以使用它的数组... – user471987 2010-10-13 07:59:35

+0

@Kragen。我相信你是对的。这并不理想,但它是我知道跨越应用程序边界的最干净的方式。 – Laramie 2010-10-13 08:13:29

3
<script type="text/javascript"> 

function GetValue() { 
var myJsVar = "<%= anyC#Variable %>"; 

//执行你想要的操作。

} 
</script> 

但记住变量“anyC#Variable”的访问说明符应该高于私有。 你可以采取“保护”或“公共”,但不是私人的。

0

C#:

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "<script language='javascript'>alert(" + abc + ");</script>", false) 

VB:

ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), "temp", "<script language='javascript'>alert(" + abc + ");</script>", False)