Flieupload is not working on ascx page - c#

I am facing a problem. I place a control ascx at aspx page. At aspx page i am using UpdatePanel. And at ascx page i use a Formview. In Formview <InsertItemTemplate> i use a control asp:FileUpload for File upload. After Selecting file, when i check FileUpload.HasFile it gives me false always. I try to fire <Triggers> but not
success because file upload is on my ascx page. In below example i am showing my problem parts.
code
FileUpload _fileUpload = FormView1.FindControl("FileUpload1") as FileUpload;
if (_fileUpload != null && _fileUpload.HasFile)
{
/// some code i write here
}
ASPX
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" />
<asp:PostBackTrigger ControlID="imagAddNew" />
<asp:AsyncPostBackTrigger ControlID="EditProduct1" />
<asp:PostBackTrigger ControlID="ImageButton1" />
</Triggers>
<ContentTemplate>
<asp:Panel ID="pnl_grid" Style="width: 100%; overflow: auto;" runat="server">
<uc1:EditProduct ID="EditProduct1" runat="server" />
</asp:Panel>
ASCX
<asp:FormView ID="FormView1" runat="server" Width="100%" ondatabinding="FormView1_DataBinding">
<InsertItemTemplate>
<table>
<tr>
<td class="label-col">
Image
</td>
<td class="data-col">
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
<td>
<asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="True" CommandName="Insert"
ImageUrl="~/images/save.gif" ValidationGroup="Inser" />
</td>
</tr>
</table>
</InsertItemTemplate>
</asp:FromView>

try this 100% working
Here Your FileUpload Control is Nested Inside the FormView so i find that control ImageButton and then added PostBackTrigger to that control. So you can Apply Same logic to GridView,Repeater,DataList,etc and your can use either ToolScriptManager
or ScriptManager to Register a PostBackControl
use Image Button like this
<asp:ImageButton ID="ImageButton1" runat="server"
OnClick="ImageButton1_OnClick" CausesValidation="True" CommandName="Insert"
ImageUrl="~/images/save.gif" ValidationGroup="Inser" />
in Your .aspx page where your are importing user control on page load use this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FormView ProductsFormView = (FormView)EditProduct1.FindControl("ProductsFormView");
FindAllTextBoxes(ProductsFormView);
}
}
private void FindAllTextBoxes(Control parent)
{
foreach (Control c in parent.Controls)
{
if (c.GetType().ToString() == "System.Web.UI.WebControls.ImageButton")
{
ImageButton ImageButton1 = (ImageButton)c.FindControl("ImageButton1");
if (ImageButton1 != null)
{
ToolScriptManager1.RegisterPostBackControl(ImageButton1);
//or ScriptManager.RegisterPostBackControl(ImageButton1);
}
}
if (c.Controls.Count > 0)
{
FindAllTextBoxes(c);
}
}
}
protected void ImageButton1_OnClick(object sender, EventArgs e)
{
ImageButton ImageButton1 = (ImageButton)sender;
FormViewRow row = (FormViewRow)ImageButton1.Parent.Parent;
FileUpload FileUpload1 = (FileUpload)row.FindControl("FileUpload1");
if (FileUpload1.HasFile)
{
}
}
if You are using ContentPlace Holder with Master page then
ContentPlaceHolder ContentPlaceHolder1 = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
ToolkitScriptManager ToolScriptManager1 = (ToolkitScriptManager)ContentPlaceHolder1.FindControl("ToolScriptManager1");
ToolScriptManager1.RegisterPostBackControl(ImageButton1);

Related

SelectedIndexChanged event of dropDownList not firing in Update Panel

SelectedIndexChanged event of dropDownList not firing in Update Panel and also set AutoPostBack="true".
Below is my Design Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddl_TypeofCampaign" runat="server" CssClass="form-control" AutoPostBack="true" OnSelectedIndexChanged="ddl_TypeofCampaign_SelectedIndexChanged" AppendDataBoundItems="true" ViewStateMode="Enabled" EnableViewState="true" >
<asp:ListItem Text="Select" Value="0"></asp:ListItem>
<asp:ListItem Text="Email" Value="Email"></asp:ListItem>
<asp:ListItem Text="SMS" Value="SMS"></asp:ListItem>
<asp:ListItem Text="Voice SMS" Value="Voice SMS"></asp:ListItem>
</asp:DropDownList>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1"
DisplayAfter="1">
<ProgressTemplate>
<div id="IMGDIV" runat="server" align="center" style="visibility: visible; vertical-align: middle; position: absolute; background-color: #fafbf6"
valign="middle">
<asp:Image ID="Image001" runat="server" ImageUrl="~/assets/img/ajax-loader.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
protected void ddl_TypeofCampaign_SelectedIndexChanged(object sender, EventArgs e)
{
Thread.Sleep(2000);
FillTemplates();
btn_Preview.Visible = false;
}
My page Load code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGrid();
FillTypeofSourcing();
FillCampaignNames();
FillTemplates();
}
}
Fill Template method where I am getting templates name base on selection.
protected void FillTemplates()
{
if (ddl_TypeofCampaign.SelectedItem.ToString() != "Select")
{
bo.Para1 = ddl_TypeofCampaign.SelectedItem.ToString();
bo.Para2 = "Stage1";//StageValue in TemplateMasterInfo Table
DataTable dt = bl.Get_Templates(bo);
ddl_TypeofTemplateName.DataSource = dt;
ddl_TypeofTemplateName.DataTextField = "TemplateName";
ddl_TypeofTemplateName.DataValueField = "TemplateId";
ddl_TypeofTemplateName.Items.Clear();
ddl_TypeofTemplateName.Items.Add(new ListItem("Select", "0"));
ddl_TypeofTemplateName.DataBind();
}
else
{
ddl_TypeofTemplateName.Items.Clear();
ddl_TypeofTemplateName.Items.Add(new ListItem("Select", "0"));
ddl_TypeofTemplateName.DataBind();
}
}
In Page Tag I mention viewStateEncryptionMode="Never" and I am using Visual Studio 2013. Below is my Page Tag details.
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ViewCandidate.aspx.cs" Inherits="ViewCandidate" validateRequest="false" enableEventValidation="false" viewStateEncryptionMode="Never" %>
Try to add Trigger to your Update Panel like shown as below
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddl_TypeofCampaign"
EventName="SelectedIndexChanged" />
</Triggers>
UPDATE
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers> //this is missing in your code posted
<asp:AsyncPostBackTrigger ControlID="ddl_TypeofCampaign" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>mydropcode </ContentTemplate> </asp:UpdatePanel>

How do I update only a panel on check changed?

<asp:UpdatePanel id="up1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:CheckBox ID="chkParent" runat="server" autopostback="true" OnCheckedChanged="chkParent_OnCheckedChanged" />
<asp:DataList ID="ChildList" runat="server" OnItemDataBound="ChildList_OnItemDataBound">
</ContentTemplate>
</asp:UpdatePanel>
protected void chkParent_OnCheckedChanged(object sender, EventArgs e)
{
this.ChildList.DataSource = this.ChildValues;
this.ChildList.DataBind();
}
On check changed of parent, child gets updated but the entire page also loads. Any way to avoid it?

unable to read fileupload1.filename when placed in UpdatePanel

I have a form where users upload their picture to the registration form.. everything worked fine until i added an updatepanel and an Image control.
I placed an update panel, inside it i place a table with Fileupload control and an image control. once the button is clicked the image is uploaded to the images folder and the preview is displayed in image control.
Before making the modification it worked fine.. but now im unable to read the FileUpload1.Filename .. below is the code
Reg.aspx
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table> <tr>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload1" runat="server" onclick="btnUpload1_Click"
Text="Upload" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</td>
</tr>
<tr>
<Td>
<asp:Image ID="Image1" runat="server" Width="147px" /></td></tr>
</table>
Reg.aspx.cs
protected void btnUpload1_Click(object sender, EventArgs e)
{
Label1.Text = FileUpload1.FileName;
try
{
var folder = Server.MapPath("~/UploadImages/");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
Label1.Text = Label1.Text + " Directory Created <br>";
}
var picUrl = Server.MapPath("~/UploadImages/"+ FileUpload1.FileName.ToString());
if (CheckFileName(picUrl) == true)
{
FileUpload1.SaveAs(picUrl);
Image1.ImageUrl = picUrl.ToString();
Label1.Text = Label1.Text + "Image Uploaded";
}
else
Label1.Text = Label1.Text +"File already exists";
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
}
private bool CheckFileName(string picUrl) {
if (File.Exists(picUrl))
return false;
return (true);
}
Now im not able to read the filename from fileupload1 control..
Please help
Add Postback Trigger in your update panel. Have a look at below code sample
ASPX:
<asp:UpdatePanel runat="server" ID="updatePanel1">
<ContentTemplate>
<asp:FileUpload runat="server" ID="fileUploader"/>
<asp:Button runat="server" ID="buttonSubmit" OnClick="buttonSubmit_OnClick" Text="Submit"/>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="buttonSubmit"/>
</Triggers>
</asp:UpdatePanel>
ASPX.cs
protected void buttonSubmit_OnClick(object sender, EventArgs e)
{
var fileName = this.fileUploader.FileName;
}

ASP.NET Update Panel Not Working Inside Web User Control

I have created a html5 canvas and javascript signature pad that I would like to implement as a web user control with an update panel to handle the button clicks. For some reason if I add the update panel and signature pad controls directly into the aspx file the auto postback events work but when I place the same code into a web user control the fields (canvas, buttons, divs, etc) appear but the auto postback no longer works. In both cases I am placing my script manager above the update panel.
Here's my ascx code:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="Signature_Pad.ascx.cs" Inherits="Controls_Signature_Pad" %>
<asp:UpdatePanel runat="server" ID="signatureUpdate" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="signatureApprove" eventname="Click" />
<asp:AsyncPostBackTrigger controlid="sigClear" eventname="Click" />
<asp:AsyncPostBackTrigger controlid="sigCancel" eventname="Click" />
</Triggers>
<ContentTemplate>
<fieldset id="SignatureFieldSet" runat="server" style=" border: 1 solid black;">
<p><asp:Label ID="signatureTextLabel" AutoPostBack="true" runat="server" Text=""></asp:Label></p>
<div id="canvasDiv" style="height: 300px; border:0px solid #000000; ">
<canvas id="canvasSignature" style="border:1px solid #000000;"></canvas>
</div>
<div id="sigButtonDiv" style=" border:0px solid #000000;">
<br /><br />
<asp:Button AutoPostBack="true" runat="server" OnClick="OnApprove" ID="signatureApprove" Text="Approve" />
<asp:Button AutoPostBack="true" runat="server" OnClick="OnClear" ID="sigClear" Text="Clear" />
<asp:Button AutoPostBack="true" runat="server" OnClick="OnCancel" ID="sigCancel" Text="Cancel" />
</div>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
Here's my ascx code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Controls_Signature_Pad : System.Web.UI.UserControl
{
private string signatureData;
private string signatureText;
public string SignatureData
{
get { return signatureData; }
set { signatureData = value; }
}
public string SignatureText
{
get { return signatureText; }
set { signatureText = value; }
}
public void OnApprove(object sender, EventArgs e)
{
UtilityClass.showMessageBox("Approve Clicked", this);
SignatureText = "Approved Clicked";
}
public void OnClear(object sender, EventArgs e)
{
UtilityClass.showMessageBox("Clear Clicked", this);
SignatureText = "Clear Clicked";
}
public void OnCancel(object sender, EventArgs e)
{
UtilityClass.showMessageBox("Cancel Clicked", this);
SignatureText = "Cancel Clicked";
}
public void Page_Load(object sender, EventArgs e)
{
signatureTextLabel.Text = signatureText;
}
}
Here's my relevant aspx:
...
<%# Register TagPrefix="mjt" TagName="SignaturePad" Src="~/Controls/Signature_Pad.ascx" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:ScriptManager ID="ScriptManager" runat="server" EnablePartialRendering="true" EnablePageMethods="true"></asp:ScriptManager>
<mjt:SignaturePad ID="SignaturePad" runat="server" Visible="true" SignatureData="" SignatureText="Test Signature Test." />
...
Adding event handlers in the code behind fixed the problem. Here's my code:
The control had three buttons that needed to trigger events (Approve, Clear, and Canceled).
In ascx.cs:
public event EventHandler Approved;
public event EventHandler Cleared;
public event EventHandler Canceled;
protected void signatureApprove_clicked(object sender, EventArgs e)
{
if(Approved != null)
Approved(this, EventArgs.Empty);
}
protected void sigClear_clicked(object sender, EventArgs e)
{
if (Cleared != null)
Cleared(this, EventArgs.Empty);
}
protected void sigCancel_clicked(object sender, EventArgs e)
{
if (Canceled != null)
Canceled(this, EventArgs.Empty);
}
In ascx:
<asp:UpdatePanel runat="server" ID="signatureUpdate" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="signatureApprove" eventname="Click" />
<asp:AsyncPostBackTrigger controlid="sigClear" eventname="Click" />
<asp:AsyncPostBackTrigger controlid="sigCancel" eventname="Click" />
</Triggers>
<ContentTemplate>
<fieldset id="SignatureFieldSet" class="fieldSetStyle" >
<p><asp:Label ID="signatureTextLabel" AutoPostBack="true" runat="server" Text=""></asp:Label></p>
<div id="canvasDiv" runat="server" >
<canvas id="canvasSignature" class="canvasStyle"></canvas>
</div>
<div id="sigButtonDiv">
<br />
<asp:Button AutoPostBack="true" runat="server" OnClick="signatureApprove_clicked" ID="signatureApprove" Text="Approve" CssClass="buttonStyle" />
<asp:Button AutoPostBack="true" runat="server" OnClick="sigClear_clicked" ID="sigClear" Text="Clear" CssClass="buttonStyle"/>
<asp:Button AutoPostBack="true" runat="server" OnClick="sigCancel_clicked" ID="sigCancel" Text="Cancel" CssClass="buttonStyle"/>
</div>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
In aspx:
<mjt:SignaturePad OnApproved="Signature_Approved" OnCanceled="Signature_Canceled" OnCleared="Signature_Cleared" ID="SignaturePad" runat="server" />
In aspx.cs:
protected void Signature_Approved(object sender, EventArgs e)
{
//Do signature approved action
}
protected void Signature_Canceled(object sender, EventArgs e)
{
//Do signature cancel action
}
protected void Signature_Cleared(object sender, EventArgs e)
{
//Do signature cleared action
}

ASP.NET: ModalPopupExtender prevents button click event from firing

Here is what I'm trying to do: Click a button on my page, which in turn makes (2) things happen:
Display a ModalPopup to prevent the user from pressing any buttons or changing values
Call my code behind method, hiding the ModalPopup when finished
Here is the ASP markup:
<asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="true"
UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSaveData" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Panel ID="pnlHidden" runat="server" style="display: none;">
<div>
<h1>Saving...</h1>
</div>
</asp:Panel>
<cc1:ModalPopupExtender ID="modalPopup"
BackgroundCssClass="modalBackground" runat="server"
TargetControlID="btnSaveData" PopupControlID="pnlHidden"
BehaviorID="ShowModal">
</cc1:ModalPopupExtender>
<asp:Button ID="btnSaveData" runat="server" Text="Save Data"
OnClick="btnSaveData_Click" />
</ContentTemplate>
</asp:UpdatePanel>
Now, here is my code behind C# code:
protected void btnSaveData_Click(object sender, EventArgs e)
{
UpdateUserData(GetLoggedInUser());
modalPopup.Enabled = false;
}
Why doesn't this work? The ModalPopup displays perfectly, but the btnSaveData_Click event NEVER fires.
UPDATE: The first suggestion did not work for me. I also tried your second suggestion (insofar as it applied to me). One minor difference on my end is that there is no button on my modal panel (pnlHidden) -- it's just a message. I did try using Javascript events on the client side, which at least did fire concurrently with my server-side event. This was good news, but I can't seem to find or grab a handle on the ModalPopupExtender or its BehaviorID. This doesn't work:
function showOverlay() {
var popup = $find('modalPopup');
popup.show();
}
popup is ALWAYS equal to null.
FINAL UPDATE: This is my final solution for getting this to work (Take specific note of the use of OnClientClick AND OnClick):
<asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="true"
UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSaveData" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Panel ID="pnlHidden" runat="server" style="display: none;">
<div>
<h1>Saving...</h1>
</div>
</asp:Panel>
<cc1:ModalPopupExtender ID="modalPopup"
BackgroundCssClass="modalBackground" runat="server"
TargetControlID="hdnField" PopupControlID="pnlHidden"
BehaviorID="ShowModal">
<asp:HiddenField ID="hdnField" runat="server" />
</cc1:ModalPopupExtender>
<asp:Button ID="btnSaveData" runat="server" Text="Save Data"
OnClientClick="showModal();" OnClick="btnSaveData_Click" />
</ContentTemplate>
</asp:UpdatePanel>
Using this Javascript function:
function showModal() { $find('ShowModal').show(); }
... And this code behind:
protected void btnSaveData_Click(object sender, EventArgs e)
{
UpdateUserData(GetLoggedInUser());
modalPopup.hide();
}
Try this.
Create a dummy hidden field:
<asp:HiddenField ID="hdnField" runat="server" />
Set the TargetcontrolID = "hdnField" in your Modal Popup declaration.
In your btnSaveData_Click event, do this:
modalPopup.Show();
Try this. It is 100% working
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Btnshow" runat="server" Text="Show" OnClick="Btnshow_Click" />
<asp:Button ID="BtnTarget" runat="server" Text="Target" Style="display: none" />
<asp:TextBox ID="TextBox1" runat="server">
</asp:TextBox>
<input type="button" value="Get" onclick="abc()" />
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="BtnTarget"
PopupControlID="Panel1">
</asp:ModalPopupExtender>
<asp:Panel ID="Panel1" runat="server" BackColor="Black" Width="300px" Height="300px">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="BtnHide" runat="server" Text="Hide Button" OnClick="BtnHide_Click" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="BtnHide" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Btnshow" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
Server side code
protected void Btnshow_Click(object sender, EventArgs e)
{
ModalPopupExtender1.Show();
}
protected void BtnHide_Click(object sender, EventArgs e)
{
ModalPopupExtender1.Hide();
}
First attempt: Try to set your ButtonID into OkControlID Tag and try again
OR
Second attempt: Call your event over javascript there seems to be some problems with click events
<div>
<cc1:ModalPopupExtender PopupControlID="Panel1"
ID="ModalPopupExtender1"
runat="server" TargetControlID="LinkButton1" OkControlID="Ok"
OnOkScript="__doPostBack('Ok','')">
</cc1:ModalPopupExtender>
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
</div>
<asp:Panel ID="Panel1" runat="server">
<asp:Button ID="Ok" runat="server" Text="Ok" onclick="Ok_Click" />
</asp:Panel>
From this example you can easily control panel show up depends on conditions instead of just immediately show up panel once you click button.
<asp:Button ID="btnAdd" runat="server" OnClick="btnAdd_Click"/>
<asp:HiddenField ID="hdnField" runat="server" />
<ajaxToolkit:ModalPopupExtender runat="server"
TargetControlID="hdnField"
ID="btnAdd_ModalPopupExtender"
PopupControlID="pnlPrintName">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="pnlPrintName" runat="server">
.
.
</asp:Panel>
//Server side code:
protected void btnAdd_Click(object sender, EventArgs e)
{
if( dt.Rows.Count == 0 )
{
btnAdd_ModalPopupExtender.Show();
}
else
{
add();
}
}
In code behind, you can do this:
if (true)
{
var script = #"Sys.Application.add_load(function() { $find('behavoirIDModal').show(); });";
ScriptManager.RegisterStartupScript(this, GetType(), "Show", script, true);
}
Change this 'behavoirIDModal'

Categories