javascript 在javascript中访问c#公共属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20524257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing c# public property in javascript
提问by Mrudang Vora
Is there any way to access the C# public properties in javascript?
有没有办法在javascript中访问C#公共属性?
For e.g. if there is following property in C# code:
例如,如果 C# 代码中有以下属性:
public int MyProperty { get; set; }
Could this property be accessed in javascript file?
可以在 javascript 文件中访问此属性吗?
回答by theLaw
there are several ways
有几种方法
<script>
var prop = <%=MyProperty %>;
</script>
using hidden fields
使用隐藏字段
html:
html:
<input id="hiddenF" type="hidden" runat="server" />
In .cs behind:
在 .cs 后面:
protected void Page_Load(object sender, EventArgs e)
{
hiddenF.Value = MyProperty;
}
then getting the value via getElementById().Value
然后通过 getElementById().Value 获取值
using ASP.NET MVC razor engine passing a model
使用 ASP.NET MVC 剃刀引擎传递模型
<script>
var prop = @Model.MyProperty;
</script>
回答by Murali Murugesan
You could refer any public/protected
property value in your .aspx page with the help of inline syntax
您可以public/protected
在 .aspx 页面中参考任何属性值inline syntax
C#
C#
public string MyProperty{get;set;}
.aspx
.aspx
<script language="javascript" type="text/javascript">
var propValue= <%= MyProperty%>; // available in window/global context
//var propValue= '<%= MyPublicMethod("parameter")%>';
</script>
JS
JS
function getMyValue(){
return propValue; // since it is written as part of page HTML, you can get it
}
some more reference for INLINE Syntax in ASP.NET
ASP.NET 中内联语法的更多参考
回答by realnero
no, but you can put the value into hidden field and access it from js.
不,但您可以将值放入隐藏字段并从 js 访问它。
or you can make server method and call it from JS.
或者你可以制作服务器方法并从JS调用它。
回答by JohnFx
That variable doesn't exist in JavaScript because it is running on a different machine than the C# code. C# is running on the server and JavaScript is running on the client's browser.
该变量在 JavaScript 中不存在,因为它运行在与 C# 代码不同的机器上。C# 在服务器上运行,JavaScript 在客户端的浏览器上运行。
Have your page write the property out either to a dynamically generated javascript var or to an HTML hidden field.
让您的页面将该属性写入动态生成的 javascript var 或 HTML 隐藏字段。