admin管理员组

文章数量:1295856

I am trying to change JavaScript src from a code behind file.

<script type="text/javascript" runat="server" id="srcSurvey" language="JavaScript" src="mypage.asp?p=2"></script>

When I am trying to access the object properties from the code behind file, no src option is available, do I need to put the src file at some other property?

I am trying to change JavaScript src from a code behind file.

<script type="text/javascript" runat="server" id="srcSurvey" language="JavaScript" src="mypage.asp?p=2"></script>

When I am trying to access the object properties from the code behind file, no src option is available, do I need to put the src file at some other property?

Share Improve this question edited May 2, 2012 at 18:02 Rob Alarcon 1,4502 gold badges18 silver badges32 bronze badges asked May 1, 2012 at 20:18 LazialeLaziale 8,22548 gold badges155 silver badges271 bronze badges 1
  • 2 You're going to have to modify the innerhtml of the page I think... – MarioDS Commented May 1, 2012 at 20:21
Add a ment  | 

2 Answers 2

Reset to default 5

You can't access the src attribute like that. HTML attributes are accessible via the .Attributes collection:

srcSurvey.Attributes["src"] = "my/directory/file.js";

Change javascript src from ASP Code Behind in the Head html tag

// this is the name of the file, it could be any name, but because
// you need it dynamic I add the number at the end.
string jsFileName = string.Format("mypage.asp?p={0}", 1);

// we add a HtmlGenericControl with the tag script (this will work for a
// css also, you just need to change script for LINK, and src for href) 
HtmlGenericControl linkDynamicJavascriptFile = new HtmlGenericControl("script");
// and the you add the relative client url of the resource
linkDynamicJavascriptFile.Attributes.Add("src", 
    ResolveClientUrl("~/" + jsFileName));
// just adding the type attribute, not necesary in html5
linkDynamicJavascriptFile.Attributes.Add("type", "text/javascript");
// we add the script html generic control to the Page Header and we're done
Page.Header.Controls.Add(linkDynamicJavascriptFile);

Previous Answer

ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
    "stackoverflow", 
    "<script type=\"text/javascript\" src=\"mypage.asp?p=2\"></script>", false);

Just change the hardcoded string containing the script tag with a dynamic one.

for example:

string code = string.Empty;
var pageNumber = PageRepository.GetPageAsString(); // get page number
code = string.Format("<script type=\"text/javascript\" src=\"mypage.asp?p={0}\"></script>", pageNumber);

ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"stackoverflow", code, false);

本文标签: cChange javascript src attribute from ASPnet Code BehindStack Overflow