Is there any way to access the C# public properties in javascript?
For e.g. if there is following property in C# code:
public int MyProperty { get; set; }
Could this property be accessed in javascript file?
Is there any way to access the C# public properties in javascript?
For e.g. if there is following property in C# code:
public int MyProperty { get; set; }
Could this property be accessed in javascript file?
there are several ways
<script>
var prop = <%=MyProperty %>;
</script>
using hidden fields
html:
<input id="hiddenF" type="hidden" runat="server" />
In .cs behind:
protected void Page_Load(object sender, EventArgs e)
{
hiddenF.Value = MyProperty;
}
then getting the value via getElementById().Value
using ASP.NET MVC razor engine passing a model
<script>
var prop = @Model.MyProperty;
</script>
You could refer any public/protected property value in your .aspx page with the help of inline syntax
C#
public string MyProperty{get;set;}
.aspx
<script language="javascript" type="text/javascript">
var propValue= <%= MyProperty%>; // available in window/global context
//var propValue= '<%= MyPublicMethod("parameter")%>';
</script>
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
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.
Have your page write the property out either to a dynamically generated javascript var or to an HTML hidden field.