Trong bài trước, mình đã trình bày cách gán giá trị của biến javascript trước khi nhúng file javascript có sử dụng biến đó. Như đã nói, cách trên có nhược điểm là mình phải đặt biến vào 1 file javascript khác. Hôm nay, mình xin trình bày 1 cách tốt hơn 1 chút. ^_^
Mình sẽ tạo thêm code để tạo file javascript, đặt giá trị của biến vào trong đó. Nhờ thế, mình sẽ không phải tạo file javascript bằng tay nữa. Dưới đây là code cho hàm tạo file và gán giá trị vào.
private void Write2File()
{
string strImageXMLFilePath = Null.NullString;
string strImageXMLFilePathInServer = Null.NullString;
strImageXMLFilePath = ModulePath + "test6.js";
strImageXMLFilePathInServer = Server.MapPath(strImageXMLFilePath);
if (File.Exists(strImageXMLFilePathInServer))
{
File.SetAttributes(strImageXMLFilePathInServer, FileAttributes.Normal);
}
string fileContent = "var temp=\"This is an advanced test\"";
//Write XML image list file file
StreamWriter objStream = File.CreateText(strImageXMLFilePathInServer);
objStream.WriteLine(fileContent);
objStream.Close();
}
Rồi mình đặt nó trong:
private void Method9()
{
Write2File();
HtmlGenericControl oLink = new HtmlGenericControl("script");
oLink.Attributes["language"] = "javascript";
oLink.Attributes["type"] = "text/javascript";
oLink.Attributes["src"] = ModulePath + "test6.js";
Control oCSS = Page.FindControl("CSS");
if (oCSS != null)
{
oCSS.Controls.Add(oLink);
}
}
Sau đó, ta làm theo các bước như đã hướng dẫn trong bài viết trước. Cách này khá hơn cách trước 1 chút nhưng vẫn chưa phải là cách tốt nhất. Hy vọng mình sẽ tìm ra được cách hay hơn. ^_^