简体   繁体   English

从ascx访问ascx.cs

[英]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. 我正在尝试从ascx文件的javascript访问ascx.cs文件中的列表.ascx.cs文件中的列表如下。

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

In My ascx i would like to access the same from the Javascript. 在My ascx中,我想从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. 请帮助我如何访问javascript中的列表。

No, because ascx controls don't represent a real URL that can be accessed from a client machine. 不可以,因为ascx控件不代表可以从客户端计算机访问的真实URL。 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. 您可能想要做的就是拥有一个aspx页面,该页面提供与您的ascx文件中当前包含的html相同的代码段。 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. 一个aspx页面不一定需要提供完整的html文档(等等),它只可以呈现您感兴趣的用户控件。

Source: calling an ascx page method using jquery 来源: 使用jquery调用ascx页面方法

I am assuming you are using ASP.NET Web forms here. 我假设您在这里使用ASP.NET Web表单。 You cannot access the variables/methods/properties etc in C# code from the javascript, as they never get rendered. 您无法从javascript中访问C#代码中的变量/方法/属性等,因为它们永远不会被渲染。 All your c# code is actually compiled in a DLL file and reside in the server. 您所有的c#代码实际上都编译在DLL文件中,并驻留在服务器中。

If you need to return the list from the server to the front-end browser(or for javascript), you can use a hidden field. 如果您需要将列表从服务器返回到前端浏览器(或javascript),则可以使用隐藏字段。 Just set the variable to value of the hidden field and access it from the javascript. 只需将变量设置为隐藏字段的值,然后从javascript中进行访问即可。

It's a public variable. 这是一个公共变量。 You can access it like following within your JavaScript code 您可以像下面在JavaScript代码中那样访问它

<%= 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... 如果您不需要对服务器端列表的写权限,则可以将其序列化为JSON并将其嵌入到JavaScript中,然后像JavaScript数组一样对其进行访问...

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: JavaScript:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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