get property from code behind into aspx page

前端 未结 5 1342
野性不改
野性不改 2021-01-14 08:33

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

相关标签:
5条回答
  • 2021-01-14 08:33

    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.

    0 讨论(0)
  • 2021-01-14 08:33

    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*

    0 讨论(0)
  • 2021-01-14 08:35

    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 讨论(0)
  • 2021-01-14 08:36

    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.

    0 讨论(0)
  • 2021-01-14 08:38

    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.

    0 讨论(0)
提交回复
热议问题