FileUpload.HasFile is always returning false - c#

FileUpload.HasFile is always returning false
<asp:FileUpload id="FileUploadControl" runat="server" style="width:240px;" />
<br />
<asp:Label runat="server" id="StatusLabel" text="" />
<asp:Button runat="server" ID="btn1" OnClick="btn1_Click" />
protected void btn1_Click(object sender, EventArgs e)
{
string filename = "";
if (FileUploadControl.HasFile)
{
try
{
filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/Uploads/") + filename);
StatusLabel.Text = filename;
}
catch (Exception ex)
{
string str = ex.Message;
}
}
}

Related

Why the image does not enter a variable?

aspx:
<asp:FileUpload runat="server" ID="PicUpload" CssClass="btn btn-sm xor"/>
aspx.cs:
PicUpload.SaveAs(Path.Combine("C:\\Users\\KeepKids\\KeepKids\\pics\\", PicUpload.FileName));
why PicUpload.FileName ="" ?
In one place I do the same action and I get the picture. and here I get ""
I am find from below link:
https://www.aspforums.net/Threads/136183/ASPNet-FileUpload-control-Issue-FileName-is-blank-always-blank/
Can you please try this:
**PicUpload.PostedFile.FileName**
Something like below:
protected void btnsubmit_Click(object sender, EventArgs e)
{
string filename = "";
if (uploadphoto.PostedFile != null)
{
filename = Path.GetFileName(uploadphoto.PostedFile.FileName);
if (filename != "")
{
uploadphoto.SaveAs(Server.MapPath("images/" + filename));
string path = "images/" + filename;
}
}
}
<asp:FileUpload ID="FileUploadControl" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload File"
onclick="UploadButton_Click" />
<br />
<asp:Label ID="lblMessage" Font-Bold="true" runat="server">
</asp:Label>
Below is the click event which picks up the filename from FileUploadControl
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
lblMessage.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
lblMessage.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}

Why Asp:GridView calls button click method in server side?

In my case i have asp:gridview with OnRowCommand calls server method but when i try to refresh my page manually then it also calls OnRowCommand method, i don't know where is the actual problem.
My Code:.aspx
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound" OnSelectedIndexChanged="CUG_OnSelectedIndexChanged" OnRowCommand="CugSubmit_onserverclick1" EnableViewState="true"BorderStyle="Solid" BorderColor="Gray" BorderWidth="1px" EditRowStyle-BorderStyle="Solid" EditRowStyle-BorderWidth="1px" EditRowStyle-BorderColor="Gray" HeaderStyle-BorderStyle="Solid" HeaderStyle-BorderWidth="1px" HeaderStyle-BorderColor="Gray" RowStyle-BorderStyle="Solid" RowStyle-BorderColor="Gray" RowStyle-BorderWidth="1px" EmptyDataRowStyle-BorderStyle="Solid" EmptyDataRowStyle-BorderColor="Black" EmptyDataRowStyle-BorderWidth="1px" SortedAscendingHeaderStyle-BorderStyle="Solid" SortedAscendingHeaderStyle-BorderColor="Black" SortedAscendingHeaderStyle-BorderWidth="1px">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Driver ID">
<ItemTemplate>
<asp:Label ID="lbl_Dri_Name" runat="server" Text='<%# Eval("VehicleNo") %>' Visible="false"></asp:Label>
<asp:TextBox ID="Dri_Name" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Dedicated">
<ItemTemplate>
<asp:Label ID="lbl_Vehitype" runat="server" Text='<%# Eval("VehicleType") %>' Visible="false"></asp:Label>
<asp:CheckBox ID="Vehitype" runat="server" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="ProcessThis" Text="Submit" />
<asp:ButtonField CommandName="Select" ItemStyle-Width="30" Text="delete" HeaderText="Delete" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
</ItemTemplate>
<FooterStyle HorizontalAlign="left" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add Row" onclick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns></asp:gridview>
My code:.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetCUGList();
}
}
protected void CugSubmit_onserverclick1(object sender, GridViewCommandEventArgs e)
{
DL.CustomerProfile ObjInput = new CustomerProfile();
BL.CustomerInputBL ObjCustomerInputBL = new CustomerInputBL();
if (e.CommandName == "ProcessThis")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
TextBox textBox = row.FindControl("Dri_Name") as TextBox;
CheckBox chk = row.FindControl("Vehitype") as CheckBox;
ObjInput.CustId = HttpContext.Current.Session["VidStr"].ToString();
ObjInput.CustName = HttpContext.Current.Session["FirstName"].ToString();
ObjInput.VehiNo = textBox.Text;
ObjInput.Update = "Insert";
if (chk.Checked == true)
{
ObjInput.VehiChk = 1;
}
else
{
ObjInput.VehiChk = 0;
}
string URL = "http://*****/CustomerServices.svc/CUGList/";
string OutStatus = ObjCustomerInputBL.GetConnection(ObjInput, URL);
var serializer = new JavaScriptSerializer();
//AllTypeDetails.Value = OutStatus;
DataSet data = JsonConvert.DeserializeObject<DataSet>(OutStatus);
string ds = data.Tables[0].Rows[0]["ErrorMessage"].ToString();
if (ds == "already exist")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number has already registered')", true);
GetCUGList();
}
else if (ds == "Not Use")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number is not in freightX')", true);
GetCUGList();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Insert Request Sent to Admin')", true);
GetCUGList();
}
}
AddNewRowToGrid();
}
else if (e.CommandName == "ProcessThisUpdate")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = Gridview1.Rows[index];
if (row.RowType == DataControlRowType.DataRow)
{
TextBox textBox = row.FindControl("Dri_Name") as TextBox;
CheckBox chk = row.FindControl("Vehitype") as CheckBox;
ObjInput.CustId = HttpContext.Current.Session["VidStr"].ToString();
ObjInput.CustName = HttpContext.Current.Session["FirstName"].ToString();
ObjInput.Update = "Update";
ObjInput.VehiNo = textBox.Text;
if (chk.Checked == true)
{
ObjInput.VehiChk = 1;
}
else
{
ObjInput.VehiChk = 0;
}
string URL = "http://*******/CustomerServices.svc/CUGList/";
string OutStatus = ObjCustomerInputBL.GetConnection(ObjInput, URL);
var serializer = new JavaScriptSerializer();
//AllTypeDetails.Value = OutStatus;
DataSet data = JsonConvert.DeserializeObject<DataSet>(OutStatus);
string ds = data.Tables[0].Rows[0]["ErrorMessage"].ToString();
if (ds == "already exist")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number has already registered')", true);
GetCUGList();
}
else if (ds == "Not Use")
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Vehicle Number is not in freightX')", true);
GetCUGList();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Update Request Sent to Admin')", true);
GetCUGList();
}
}
}
}

model binding webform TryUpdateModel not Working

I have a simple formview and simple modelbinding in webform:
<asp:FormView ID="frm" ItemType="SabaDoor2.Models.Content" SelectMethod="frm_GetItem" UpdateMethod="frm_UpdateItem" DataKeyNames="Id" runat="server">
<ItemTemplate>
<fieldset>
<legend>
<asp:Label ID="lblName" Text='<%# Item.Name %>' runat="server"></asp:Label>
</legend>
<p>
<label>descripion :</label>
<asp:Label ID="lblDescription" Text='<%# Item.Description %>' runat="server"></asp:Label>
</p>
<p>
<asp:Button ID="btnEdit" Text="edit" CommandName="Edit" runat="server" />
</p>
</fieldset>
</ItemTemplate>
<EditItemTemplate>
<fieldset>
<legend>
<asp:Label ID="lblName" Text='<%# Item.Name %>' runat="server"></asp:Label>
</legend>
<p>
<label>description :</label>
<asp:TextBox ID="txt" Text='<%# Item.Description %>' runat="server" ></asp:TextBox>
</p>
<p>
<asp:Button CommandName="Update" ValidationGroup="mainPropertyGroup" runat="server" ID="btnUpdate" Text="update" />
<asp:Button CommandName="Cancel" ValidationGroup="mainPropertyGroup" runat="server" ID="btnCancel" Text="cancel" />
</p>
</fieldset>
<br />
</EditItemTemplate>
</asp:FormView>
and in code:
Models.Model1Container _db = new Models.Model1Container();
protected void Page_Load(object sender, EventArgs e)
{
bindEvents();
lblResult.ForeColor = System.Drawing.Color.Green;
lblResult.Text = "";
if (!IsPostBack)
{
}
else
{
}
}
private void bindEvents()
{
frm.ItemUpdated += frm_ItemUpdated;
}
void frm_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
{
if (e.Exception == null)
{
lblResult.ForeColor = System.Drawing.Color.Green;
lblResult.Text = "done!";
}
else
{
lblResult.ForeColor = System.Drawing.Color.Red;
lblResult.Text = "error:" + e.Exception.Message;
e.KeepInEditMode = true;
}
}
public SabaDoor2.Models.Content frm_GetItem([System.Web.ModelBinding.QueryString("Id")]int? Id)
{
return _db.Contents.Find(Id);
}
// The id parameter name should match the DataKeyNames value set on the control
public void frm_UpdateItem(int Id)
{
SabaDoor2.Models.Content item = null;
item = _db.Contents.Find(Id);
if (item == null)
{
// The item wasn't found
ModelState.AddModelError("", String.Format("Item with id {0} was not found", Id));
return;
}
var result = TryUpdateModel(item);
if (ModelState.IsValid)
{
_db.SaveChanges();
}
}
public override void Dispose()
{
_db.Dispose();
base.Dispose();
}
tryUpdateModel return true but my model(description field) doesn't update
:(
I find out logical error:
i have to initialize BindItem.Name property instd of item.Name
Text='<%# BindItem.Description %>'

Doc file does not download from UserControl in asp.net

I have user control which contain a grid with candidate data. There a columns candidate name with template field link button. I have attached a rowcommand event on which I am downloading a word file. I have download doc file code which download my doc file from simple web page but this code is not working on user control. Can any one help me to out this problem. its giving the error response is not available
<asp:GridView ID="grdCandidate" runat="server" AutoGenerateColumns="false"
OnRowDataBound="grdCandidate_RowDataBound"
onrowcommand="grdCandidate_RowCommand">
<Columns>
<asp:BoundField DataField="Candidate ID" HeaderText="Candidate ID" />
<asp:TemplateField>
<HeaderTemplate>
Candidate Name
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkResume" CommandName="Download" CommandArgument='<%#Eval("Candidate ID") %>'
runat="server" Text='<%#Eval("Candidate Name") %>' ToolTip='<%# "Download Resume - " + Eval("Candidate Name") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void grdCandidate_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Download")
{
byte[] Attachment = null;
string Extension = string.Empty;
string Resume = "Resume";
ClsCandidateManager objCandidateManager = new ClsCandidateManager();
ClsSecureManager objSecureManager = new ClsSecureManager();
Attachment = objCandidateManager.GetCandidateAttachment(Convert.ToInt32(e.CommandArgument), out Extension);
if (Attachment != null && Attachment.Length > 0)
{
try
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
if (Extension == ".pdf")
{
Response.ContentType = "application/pdf";
}
else
{
Response.ContentType = "application/vsd-msword";
}
Response.AddHeader("content-disposition", "attachment;filename=" + Resume + Extension);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(Attachment);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
string str = ex.Message + ex.InnerException;
}
}
else
{
//ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('Resume is not Uploaded !');</script>");
}
}
}
catch (Exception ex)
{
string str = ex.Message + ex.InnerException;
}
Use the UpdatePanel as shown below,
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="View" OnClick="lnkDownload_Click"
CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="lnkDownload" />
</Triggers>
</asp:UpdatePanel>

Repeater control not updating with ItemCommand

I have a Repeater control, that I have now reduced to just changing text in a text box when clicking the associated button.
However, this is not happening.
Here is my code so far:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:Repeater ID="rptPdfList" runat="server" OnItemCommand="rptPdfList_ItemCommand">
<HeaderTemplate>
<table>
<tr>
<td>File Name</td>
<td></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblName" runat="server" Text=<%#Eval("FileName") %>></asp:Label>
</td>
<td>
<asp:Button ID="btnLoad" runat="server" Text="Load" CommandName="LoadDoc"/>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btnLoad" runat="server" Text="Load" OnClick="btnLoad_Click" /><br />
<iframe runat="server" id="pdfHolder"></iframe>
<br />
<asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetFiles();
}
private void GetFiles()
{
rptPdfList.DataSource = Pdf();
rptPdfList.DataBind();
}
protected void rptPdfList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
Label lblName = (Label)e.Item.FindControl("lblName");
switch (e.CommandName)
{
case "LoadDoc":
//xpdfHolder.Attributes.Add("src", "PDF/" + lblName.Text);
lblTest.Text = "test";
lblName.Text = "oops";
break;
}
}
public static List<PdfList> Pdf()
{
string pdfDir = HostingEnvironment.MapPath("~") + #"PDF\";
DirectoryInfo directory = new DirectoryInfo(pdfDir);
FileInfo[] pdfFiles = directory.GetFiles("*.pdf", SearchOption.AllDirectories);
List<PdfList> pdfLists = pdfFiles.Select(pdfFile => new PdfList
{
FileName = pdfFile.Name
}).ToList();
return pdfLists;
}
}
public class PdfList
{
public string FileName { get; set; }
}
Ca anyone see where I went wrong?
Edit, added all the code
Change this:
protected void Page_Load(object sender, EventArgs e)
{
GetFiles();
}
to this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GetFiles();
}
You are calling the GetFiles() each time so it is always returning to the initial state.
I am binding your repeater like this and it works fine for me, Just place your binding function in
if (!Page.IsPostBack)
condition :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (DataClassesDataContext dc = new DataClassesDataContext())
{
var v = (from s in dc.t_employees select s).ToList();
rptPdfList.DataSource = v;
rptPdfList.DataBind();
}
}
}
protected void rptPdfList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
Label lblName = (Label)e.Item.FindControl("lblName");
switch (e.CommandName)
{
case "LoadDoc":
//xpdfHolder.Attributes.Add("src", "PDF/" + lblName.Text);
lblTest.Text = "test";
lblName.Text = "oops";
break;
}
}

Categories