user233272
user233272

Reputation: 65

get property from code behind into aspx page

Is it possible to get the property(get; set; ) say Name from code behind(aspx.cs) file into jquery?

Upvotes: 4

Views: 20982

Answers (5)

Sridhar
Sridhar

Reputation: 9084

you can use a hidden input control and set the value of it inside the property. then you can access the value of the property by accessing the value of hidden variable.

ex

aspx page

<asp:HiddenField id="hiddenField1" runat="server">

code behind

Public Property MyProperty as String
Get
   Return hiddenField1.Value
End Get
Set(value as string)
  hiddenField1.Value = value
End Set

jquery

var hValue = $('#<%= hiddenField1.ClientID %>').val();

Upvotes: 0

Hannes Nel
Hannes Nel

Reputation: 532

In the codebehind add the following:

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ClientVariable", "var clientVariable = '" + clientValue + "';", true);

where clientValue is the value you would like to be accessible, by using the normal javascript variable clientVariable in your client code.

Don't leave out the 'true' parameter at the end, as the default is to not add script tags, which prevents the script from working.

Upvotes: 0

womp
womp

Reputation: 116977

Yep. If your script is inline in the aspx page, simply use the ASP tags to get it into the script.

<html.....
<script type="text/javascript">
    public function myJSFunction()
    {
        var x = '<%= Name %>';
       ...
    }
</script>

If your script isn't inline, i.e. it's coming from a separate javascript file, you have a couple of options.

  1. You can add the variables that you need into the page using the technique above, and then your external javacript can reference it.

  2. You can make the external javascript file a web resource by changing it's content type to "Embedded Resource" in the properties window, and then using the following:

    [assembly: WebResource("myJS.js", "text/javascript", PerformSubstitution=true)]

The use of the "PerformSubstitution" flag on a WebResourceAttribute will make it so that the file is run through the asp parser before it is rendered, and it will replace any ASP tags it find in the file. Web resources have some drawbacks though so you should read up on them before deciding to use them.

Upvotes: 6

Brian Kim
Brian Kim

Reputation: 25336

You can either use protected property like this, var name = '<%= Name %>';

Or generate JavaScript code from codebehind and register to client side by using ClientScript.RegisterClientScript*

Upvotes: 1

rossipedia
rossipedia

Reputation: 59367

Yes, depending on your framework:

<script type="text/javascript">
var someProp = "<% = this.PropertyName; %>";
</script>

You may run into encoding issues, so make sure you escape the value for javascript.

Upvotes: 7

Related Questions