2012-05-01 21 views
1

コードビハインドファイルからJavaScript srcを変更しようとしています。JavaScriptのsrc属性をASP.netから変更するコードの後ろ

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

私は分離コードファイルからオブジェクトのプロパティにアクセスしようとしていた場合、何のSRCオプションが利用できない、私はいくつかの他のプロパティでのsrcファイルを配置する必要がありますか?

enter image description here

+2

あなたは私が考えるページのinnerHTMLプロパティを変更する必要があるとしている... – MarioDS

答えて

5

あなたはそのようなsrc属性にアクセスすることはできません。 HTML属性は.Attributesコレクションからアクセスできます:

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

私はその仕事をすることはできません、コンパイラは、JSファイル、CS1012を読み取ろうとします:文字リテラルに文字数が多すぎますが、何が起こっていますか? –

+0

は実際のJSをsrcにドロップしようとしているように聞こえます。上記のように、ファイルを指す文字列を入れてください。 – Jason

+0

ああ、二重引用符ではなく、ファイルパスを一重引用符で囲むこともできます:) – Jason

2

変更

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

前の回答ヘッドhtmlタグ内の後ろASP.netコードからJavaScriptのSRC

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

dynaを使ってscriptタグを含むハードコードされた文字列を変更するだけですマイク1。例えば

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); 
+0

コードはページ上のその位置に正確に配置する必要があるため、html部分に何を入れる必要がありますか?どうやってするか?また、あなたは何のために 'stackoverflow'を使用していますか? Thx – Laziale

+0

"stackoverflow"はスクリプトの一意な識別子です。これは有効なC#文字列 –

+0

になります。どこからPageRepository関数を取得しましたか?コードでそのオプションを見つけることができません。 Thx – Laziale

関連する問題