Question

I'm trying to use jQuery in a Sandboxed Visual WebPart (2010):

protected void Page_Load(object sender, EventArgs e)
{
    string jQuerySrc = Page.ClientScript.GetWebResourceUrl(this.GetType(), "ProjectNS.Scripts.jquery.min.js"); // Correctly assigned in debugger
    // Script tag not present in HTML (regardless of whether the WebResources call would actually succeed or fail.)
    Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "ProjectNS.Scripts.jquery.min.js", jQuerySrc); 
}

I've also now tried this alternative with no apparent change:

ScriptManager.RegisterClientScriptResource(Page, this.GetType(), "ProjectNS.Scripts.jquery.min.js");

When I deploy and run, this code seems to run fine and generates no errors. Unfortunately, the resulting page's html does not contain the references to the script.

If this is indeed a silent failure due to Sandbox restrictions, I guess I understand. But it could be another oversight.

Can anyone speak to whether a javascript file can be included in this way in a Sandboxed Visual WebPart? If it should be working, any ideas on why it isn't?

If it cannot work this way, is there an alternative?

Thanks!

PS. Possibly related - Page.Header is null. This I discover when attempting to add an HtmlLink for a css file. Not sure what to think.

Était-ce utile?

La solution

The Page object you're getting in the Sandboxed webpart isn't the real page, so this in one of the things that won't work.

Option 1: Render in RenderContents
You can manually render your script include in RenderContents:

protected override void RenderContents(HtmlTextWriter writer)
{
  string jQuerySrc = Page.ClientScript.GetWebResourceUrl(this.GetType(), "ProjectNS.Scripts.jquery.min.js");
  writer.WriteLine("<script type='text/javascript' src='{0}'></script>", jQuerySrc);
  base.RenderContents(writer);
}

Option 2: Include from CDN
If your users have internet access then you can just put this into your .ascx file:

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
  jQuery.noConflict();
</script>

Autres conseils

This is the best solution I found: https://github.com/eirikb/sppreload

It uses JS to add the script to the head element, and it also makes sure the resource is only loaded once.

Licencié sous: CC-BY-SA avec attribution
Non affilié à sharepoint.stackexchange
scroll top