开发者

get property from code behind into aspx page

开发者 https://www.devze.com 2022-12-14 19:31 出处:网络
Is it possible to get the property(get; set; ) say Name from code behind(aspx.cs) file开发者_StackOverflow社区 into jquery?Yes, depending on your framework:

Is it possible to get the property(get; set; ) say Name from code behind(aspx.cs) file开发者_StackOverflow社区 into jquery?


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.


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.


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*


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.


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号