asp.net - What is the significance of the Type parameter in the RegisterClientScriptBlock method call? - Stack Overflow

admin2023-02-27  376

This is an example of RegisterClientScriptBlock

 Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "key","scriptblock", True)

Why do the method needs the type as the first parameter ?

Thanks.

Answers:

This is an example of RegisterClientScriptBlock

 Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "key","scriptblock", True)

Why do the method needs the type as the first parameter ?

Thanks.

Answers:

From the MSDN docs: "A client script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates."

Basically it gives you an additional way to uniquely identify your scripts. You could have the same key value across different types of controls.

Answers:

I've wondered about this myself. As far as I can see in Reflector, it's not used by RegisterClientScriptBlock() directly, it is only passed through to be used by the GetHashCode() method of the ScriptKey class. There it probably serves to uniquely identify the script block further beyond just the user-supplied key, since it is linked to the specified type.

Answers:

There a post on why this could lead to trouble, but I've never actually encountered this. It comes down to this: when you inherit from a control that has this piece of code, the GetType will return something else. This way, the key will differ and the script will be added a second time if you have both controls on your page. This could potentially lead to javascript problems.

The solution would be to not use GetType but typeof() instead. In VB.Net:

Page.ClientScript.RegisterClientScriptBlock(GetType(MyClass), "key","scriptblock", True)

But again, this is an exceptional case.

转载请注明原文地址:https://www.jcdi.cn/read-201025.html
New Post(0)