The design of the functionality for the image uploading in the categories management page baffles me. We have a text box for the image url and separately a file uploader user control. So we can do the file upload and then we have to copy and paste the url into the text box?
Hey, I'm a Spaniard, you know we're lazy by nature, so that seemed like a lot of work to me. Why not just have the url show in the text box once the file is succesfully uploaded? I still don't know why we couldn't have the file uploader in the Image part of the details view control, but hey, at least this would be taken care of.
So my solution was to create an event in the file uploader user control that would be called from the upload button click event once the file was uploaded. To do that I created a delegate and the event. At the same time, I created a public property in the user control to hold the fileUrl. Then in the ManageCategories page I handled the event by setting the text property of the txtImageUrl control to the FileUrl property from the control.
The code for the control event creation is the following:
Code:
public delegate void FileUploadedEventHandler(object sender, EventArgs e);
public partial class FileUploader : System.Web.UI.UserControl
{
private string _fileUrl = String.Empty;
public string FileUrl
{
get { return _fileUrl; }
private set { _fileUrl = value; }
}
public event FileUploadedEventHandler FileUploaded;
....... // Other code
}
The code for the btnUpload OnClick event handler within the File Uploader user control would be
Code:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (filUpload.PostedFile != null && filUpload.PostedFile.ContentLength > 0)
{
try
{
// Create the folder if it doesn't exist.
string dirUrl = String.Format("{0}Uploads/{1}", ((BasePage)this.Page).BaseUrl, this.Page.User.Identity.Name);
string dirPath = Server.MapPath(dirUrl);
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
string fileUrl = String.Format("{0}/{1}", dirUrl, Path.GetFileName(filUpload.PostedFile.FileName));
filUpload.PostedFile.SaveAs(Server.MapPath(fileUrl));
this.FileUrl = fileUrl;
lblFeedbackOK.Visible = true;
lblFeedbackOK.Text = String.Format("File successfully uploaded: {0}", fileUrl);
if (FileUploaded != null)
FileUploaded(this, e);
}
catch (Exception exc)
{
lblFeedbackKO.Visible = true;
lblFeedbackKO.Text = exc.Message;
}
}
}
Finally in the ManageCategories Page the event handler for the FileUploaded event:
Code:
protected void filUpload_FileUploaded(object sender, EventArgs e)
{
((TextBox)dvwCategory.FindControl("txtImageUrl")).Text = filUpload.FileUrl;
}
Let me know if you have an easier way of handling this. I was wondering if creating a custom web event and raising it... but I'm not really sure how that works.