简体   繁体   中英

Accessing ascx.cs from ascx

I am trying to access a list in the ascx.cs file from the javascript of the ascx file.The list in the ascx.cs file is as follows.

public List<String> samplelist
{
     get { return samplelist; }
     set { samplelist = value; }
}

In My ascx i would like to access the same from the Javascript.

<script>
  function calllist() {
  // I want to access the  list named "samplelist" here.
  }
 </script>

Please help me how to access the list in the javascript.

No, because ascx controls don't represent a real URL that can be accessed from a client machine. They're purely server-side meant to embed in other pages.

What you might want to do is just have an aspx page that provides the same snippet of html you currently have in your ascx file. An aspx page doesn't necessarily need to provide a full html document ( etc.), it can just render the user control you're interested in.

Source: calling an ascx page method using jquery

I am assuming you are using ASP.NET Web forms here. You cannot access the variables/methods/properties etc in C# code from the javascript, as they never get rendered. All your c# code is actually compiled in a DLL file and reside in the server.

If you need to return the list from the server to the front-end browser(or for javascript), you can use a hidden field. Just set the variable to value of the hidden field and access it from the javascript.

It's a public variable. You can access it like following within your JavaScript code

<%= samplelist %>

If you don't need write access to the server-side list, you can serialize it to JSON and embed it in JavaScript, then access it like a JavaScript array...

Code behind:

using System.Web.Script.Serialization;

public List<String> samplelist
{
     get { return samplelist; }
     set { samplelist = value; }
}

public string sampleListJson()
{
    var jsonSerializer = new JavaScriptSerializer();
    return jsonSerializer.Serialize(samplelist);
}

JavaScript:

<script>
    var samplelist = <%= sampleListJson() %>;

    function calllist() {
        alert(samplelist[0]);  
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM