Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get property from code behind into aspx page

Tags:

jquery

c#

asp.net

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

like image 863
user233272 Avatar asked Dec 09 '22 18:12

user233272


2 Answers

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.

like image 52
rossipedia Avatar answered Dec 23 '22 10:12

rossipedia


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.

like image 24
womp Avatar answered Dec 23 '22 11:12

womp