我想在ASP Web表单中将一串数据从C#传输到JavaScript。我的方法是在C#中将数据设置为ASP标签的文本,然后在JS中按ID获取标签的文本。
C#代码(ascx.cs文件):
List<Event> eventList;
protected void Page_Load(object sender, EventArgs e)
{
string message = string.Empty;
SPSite franasabank = new SPSite("http://lbshrptweb/sites/fransabank/");
SPWeb calendar = franasabank.OpenWeb();
SPList list = calendar.Lists["Fransabank Calendar"];
eventList = new List<Event>();
foreach (SPListItem oItem in list.Items)
{
// Access each item in the list...
DateTime startTime = (DateTime)oItem["Start Time"];
DateTime endTime = (DateTime)oItem["End Time"];
string status = (String)oItem["Status"];
string title = oItem.Title;
string description = (String)oItem["Description"];
Event calendar_event = new Event(startTime, endTime, status, title, description);
eventList.Add(calendar_event);
}
foreach (Event item in eventList)
{
message += item.Title + " " + item.Description + item.StartDate + "-" + item.EndDate + "-" + item.Status + "\n";
}
Label1.Text = message;
}
HTML代码段显示标签(ascx文件):
<div data-ng-app="Calendar">
<div data-ng-controller="CalendarController" id="mycontroller">
<div class="row " data-ng-init="Initialize()">
<asp:Label ID="Label1" runat="server" Text="Label" ></asp:Label>
JavaScript代码:
<script>
var a = document.getElementById('<%= Label1.ClientID %>');
console.log(a);
</script>
我在变量'a'中收到数据为null。我试过了
var a = document.getElementById('<%= Label1.ClientID %>').innerHTML;
但它也是空的
答案 0 :(得分:0)
听起来像Javascript在加载标签之前运行
将js放在页面上的<asp:Label>
之后。最好在</body>
之前:
<script>
var a = document.getElementById('<%= Label1.ClientID %>');
console.log(a);
</script>
</body>
或者,您可以使用jQuery $(document).ready()
包围代码块:
<script>
$(document).ready(function () {
var a = document.getElementById('<%= Label1.ClientID %>');
console.log(a);
});
</script>