如何在客户端脚本中访问servercontrols [英] how access servercontrols in client scripts

查看:53
本文介绍了如何在客户端脚本中访问servercontrols的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在客户端脚本中访问服务器控件?

how i can access servercontrols in client scripts?

推荐答案

您可以使用<%=%>标签在javascript中访问服务器代码.例如,以下功能将提示文本值.

You can access server code in you javascript using <%=%> tag. E.g The following function will alert the text value.

function AlertValue() {
   var tbValue=document.getElementByID("<%=textbox1.ClientID%>").value;
   alert(tbValue);
}


这是一个非常开放的问题.您不能直接访问在C#中运行的对象的服务器端实例,但是可以设置HTML对象客户端的属性.提交表单后,更改将返回给服务器,就好像用户已对其进行了编辑一样.要在JavaScript中设置元素的属性或值,您需要做两件事:1)对对象本身的引用和2)知道要设置的内容.例如,如果我创建了一个TextBox服务器端,然后将其添加到我的页面中;要更改Javascript中TextBox的值,我将执行以下操作:

This is a very open question. You cannot directly access the server side instance of the object that runs in C# but you can set the properties of the HTML object client side. The changes are returned to the server when the form is submitted, as if the user had edited them. To set the properties or values of an element in JavaScript you need two things: 1) A reference to the object itself and 2) to know what you want to set. For instance, if I had created a TextBox server side and then added it to my page; To change the value of the TextBox in Javascript I would do something like the following:

//JavaScript

//Replace 'ATextBox' with the Id of your control.
document.getElementById("ATextBox").value = "Hello world!";



然后,用户可以提交表单和值"Hello World!".将被提交到服务器.但是,这有一个问题:Asp.Net会在服务器端设置Id标签,以使它们看起来不一样.要解决此问题,您必须在浏览器中使用开发人员工具,查看您要更改的元素的实际ID,然后将其用作JavaScript中的ID.我发现Asp.Net C#通常采用ID服务器端,只是在其前面放置"ct100_",这意味着客户端ID(JavaScript中的ID)为"ct100_ATextBox".

进一步阅读:
W3Schools JavaScript教程 [ W3Schools AJAX教程 [ W3Schools HTML DOM对象参考 [



And then the user coulod submit the form and the value "Hello World!" would be submitted to the server. However, there is an issue with this: Asp.Net mangles Id tags set server side so they don''t appear the same. To solve this issue you must use Developer Tools in your browser, look at the actual Id of the element you are trying to change and then use that as the Id in your JavaScript. I have found that Asp.Net C# commonly takes the Id server side and just puts ''ct100_'' on the front of it meaning the client side Id, the Id in JavaScript, is then ''ct100_ATextBox''.

Further reading:
W3Schools JavaScript Tutorial[^]
W3Schools AJAX Tutorial[^] - For submitting forms/information to a server without having to have the user click on something and getting a return value without a page refresh.
W3Schools HTML DOM Objects Reference[^] - All the elements in HTML and their properties plus how to set them in JavaScript.

Hope this helps,

Ed :)


这篇关于如何在客户端脚本中访问servercontrols的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆