7

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?

6
  • are you trying to access it in aspx page ?If so see stackoverflow.com/a/1089271/961113 Commented Dec 11, 2013 at 16:15
  • 1
    Nope, not from JS directly. You would have to print the value of the property server-side in the ASPX, by means of `var javaScriptVariable = '<%= object.PropertyValue %>'; or something like that/ Commented Dec 11, 2013 at 16:15
  • @Habib: I was not trying to access it in aspx page. Commented Dec 11, 2013 at 16:38
  • @JasonEvans: Thanks. If there is no other way, I would access it as you said in aspx page and then use that javascript variable in my .js file Commented Dec 11, 2013 at 16:39
  • Habib and Jason: Thanks for your resposne. As you both mentioned, I would use this way to access properties as I think this is one of the best ways we could do it. Commented Dec 11, 2013 at 16:48

4 Answers 4

9

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>
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

0

no, but you can put the value into hidden field and access it from js.

or you can make server method and call it from JS.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.