How do I embed javascript directly into my ASP.net Custom Control?
I am building my first user control and I would like to package the javascript required for the control with the assembly so the end user does not have to worry about including dependencies. I've followed a tutorial from Scott Mitchell (https://web.archive.org/web/20210510023046/http://aspnet.4guysfromrolla.com/articles/080906-1.aspx) but I can't seem to get it to work right.
Here is what I've done so far:
I've created a CollapsiblePanel.js file that contains the following function:
function TogglePanel(panelId) {
// $(panelId + ' .PanelContent').toggle();
alert(panelId);
}
Under the properties panel I set the Build Action to "Embedded Resource". This file resides in a scripts/ directory inside my class library project. The root namespace of my project is webstation.WebControls so if my understanding is correct I should be referencing the js file via "webstation.WebControls.scripts.CollapsiblePanel.js"
I've added the following line just before my class declaration for the custom control:
<Assembly: WebResource("webstation.WebControls.scripts.CollapsiblePanel.js", "text/javascript")>
开发者_Python百科
I've overridden the OnPreRender event in my Custom Control and added the following:
Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
Page.ClientScript.RegisterClientScriptInclude("wsWebControlsCollapsiblePanel", _
Page.ClientScript.GetWebResourceUrl(Me.GetType(), "webstation.WebControls.scripts.CollapsiblePanel.js"))
MyBase.OnPreRender(e)
End Sub
When I render my control I have a button with the function "TogglePanel(this.id);" in the onclick event, but when I click the button I get an error saying that the function is not defined. If anyone knows how I might begin using my embedded javascript I would really appreciate the help,
Mike
Found it,
The problem was I included 'scripts' in the resource name so that I had "webstation.WebControls.scripts.CollapsiblePanel.js"
I decided to try it so I had: "webstation.WebControls.CollapsiblePanel.js"
and that did the trick.
It's a little confusing because all the documentation specifically states including the path as part of the naming convention, but perhaps I did something wrong when including a folder in the project.
Mike
精彩评论