网络编程ASP.NET的几个技巧

王朝asp·作者佚名  2006-11-24
窄屏简体版  字體: |||超大  

1.显示通过代码生成的图片

把生成图片的代码放在一个aspx页面中,在PageLoad事件中把图片写入输出流:

private void Page_Load(object sender, System.EventArgs e) {

string code = Request.Params["code"];

Bitmap image = DrawImage(code);

Response.ContentType = "image/gif";

image.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Gif);

Response.End();

}

在需要引用图片的地方,设定图片URL为生成图片的aspx页面:

ImageCode.ImageUrl = "CodeImage.aspx?code="+code;

2.使用System.Web.HttpContext.Current来实现一些页面中常用的方法,比如:

public class WebApp{

public static void ShowMessage(string message){

HttpContext.Current.Response.Write ("<script language=javascript>alert('"+message+"')</script>");

}

public static string CurrentUser{

get{

return HttpContext.Current.Session["UserID"]+"";

}

}

}

3.在自定义的Web控件中,把Javascript脚本文件编译为内嵌的资源,然后从资源中读取脚本并注册。

public class Res {

public static StreamReader GetStream(Type type,string name){

//Assembly assembly = Assembly.GetAssembly(type);

Assembly assembly = type.Assembly;

Stream stream = assembly.GetManifestResourceStream(type,name);

return new StreamReader(stream);

}

}

public class ScriptControl : Control {

/// <summary>

/// Register Client Script Block

/// </summary>

/// <param name="control">custom web control</param>

/// <param name="scriptfile">resource script file name</param>

public void RegisterScript(string scriptfile){

if (!this.Page.IsClientScriptBlockRegistered(scriptfile)) {

StreamReader reader = Res.GetStream(this.GetType(),scriptfile);

using(reader){

string script

= "<script language=\"javascript\" type=\"text/javascript\">\r\n<!--\r\n"

+ reader.ReadToEnd()

+ "\r\n//-->\r\n</script>";

this.Page.RegisterClientScriptBlock(scriptfile, script);

}

}

}

}

[DefaultProperty("Text"),

ToolboxData("<{0}:ShowDialogListBox runat=server></{0}:ShowDialogListBox>")]

public class ShowDialogListBox : ScriptControl {

......

protected override void OnInit(EventArgs e) {

this.RegisterScript("EnDeListBox.js");

}

......

}

4.在web.config文件中定义默认的页面继承类型。

<pages pageBaseType="Msdn.Page" />

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航