简体   繁体   English

ASP NET自定义服务器控件中的事件

[英]Events in ASP NET Custom Server Control

I wonder what is the difference between that two methods of calling postback in my custom server control: 我想知道在我的自定义服务器控件中调用回发的两种方法之间的区别是什么:

Page.ClientScript.GetPostBackEventReference(new PostBackOptions (this)) 

or manually 或手动

__doPostBack('MyControl1', '')

which of these two solutions is better to prefer and why? 这两种解决方案中的哪一种更好,为什么?

I find that as a general rule of thumb it's better avoid hardcoding IDs in JavaScript that way. 我发现,作为一般经验法则,最好避免以这种方式在JavaScript中对ID进行硬编码。 I've also found that it's better to let ASP generate things for you where it can so ASP gets what ASP is expecting. 我还发现,最好让ASP在可能的地方为您生成事物,以便ASP获得ASP的期望。

If you let ASP generate your __doPostback for you then you know that ASP knows which control you're talking about. 如果让ASP为您生成__doPostback,那么您就会知道ASP知道您在谈论哪个控件。 You're going to get the correct eventtarget and eventargument for the control in question when you use ClientScript.GetPostbackEventReference. 使用ClientScript.GetPostbackEventReference时,将为所涉及的控件获取正确的eventtarget和eventargument。 Even if you move it around in the mark-up or otherwise do something to change its clientID ASP still knows what you're talking about because its generating the JavaScript. 即使您在标记中四处移动或以其他方式更改其clientID,ASP仍然知道您在说什么,因为它生成了JavaScript。

Granted, you could avoid that particular pitfall with a well-place <%= MyControl1.ClientID%>, but I think keeping it in the back-end is cleaner. 当然,您可以使用适当的<%= MyControl1.ClientID%>避免这种特殊的陷阱,但我认为将其保留在后端会更干净。

I tried to find an article or blog talking about this to back me up so this wouldn't be strictly an opinion, but most of what I found was instructional on HOW to use it rather than an they WHY you should use it. 我试图找到一篇有关此事的文章或博客来支持我,所以这并不是严格的意见,但是我发现的大多数内容都是关于如何使用它的说明性的,而不是为什么您应该使用它。

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

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