Wednesday, November 03, 2004

Set Form Enctype (ASP.NET)

This UserControl sets the EncType of the server side form on an ASP.NET page. Useful if you have another UserControl that uploads a file, as it prevents the need to change the parent page EncType (to "multipart/form-data").

Code:

<%@ Control Language="C#" %>
<script runat="server">
public string EncType = "";

void Page_Load(object sender, EventArgs e)
{
	SetEncType(EncType);
}

protected void SetEncType(string EncType)
{
	// continue if enctype is valid
	if(EncType=="text/plain" || EncType=="multipart/form-data" || EncType=="application/x-www-form-urlencoded") {
		Control container = this.Parent;
		while( container.GetType() != typeof(UserControl) && container.GetType() != typeof(HtmlForm) && container.GetType() != typeof(Page) ) {
			container = container.Parent;
		}
		HtmlForm form = container as HtmlForm;
		if ( form != null) {
			form.Enctype = EncType;
		}
	}
}
</script>

Example use:

Register tag: <%@ Register TagPrefix="Form" TagName="EncType" Src="formenc.ascx" %>. Add at start of UserControl page: <Form:EncType EncType="multipart/form-data" runat="server" />

No comments: