3

コード ビハインド ファイルから JavaScript src を変更しようとしています。

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

コード ビハインド ファイルからオブジェクト プロパティにアクセスしようとすると、src オプションが利用できません。src ファイルを他のプロパティに配置する必要がありますか?

ここに画像の説明を入力

4

2 に答える 2

5

srcそのような属性にアクセスすることはできません。HTML 属性は、.Attributesコレクションを介してアクセスできます。

srcSurvey.Attributes["src"] = "my/directory/file.js";
于 2012-05-01T20:26:31.387 に答える
3

ヘッドhtmlタグのASP.netコードビハインドからjavascriptsrcを変更します

// 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);

前の回答

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

スクリプトタグを含むハードコードされた文字列を動的な文字列に変更するだけです。

例えば:

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);
于 2012-05-01T20:34:32.553 に答える