request file not working in asp.net - c#

i need to request file from fileupload that is created in html. my question is quite simple how do i do this?
i know there is this option : HttpPostedFile File = Request.Files["imagem"]; but when i try to do that my File returns NULL.
I dont know what am i doing wrong, but even this simple code example is not working and i dont know why .
<body>
<form id="form1" runat="server">
<div>
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile File = Request.Files["imagem"];
if ( File != null)
Response.Write("Sucesso");
}
</form>
</body>
and here is my aspx code example :
<input type="file" name="image" class="image-upload" /></div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
can any one explain what am i doing wrong ? thank you

Might just be a typo on here, but change your imagem to image
protected void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile File = Request.Files["image"];
if ( File != null)
Response.Write("Sucesso");
}
In your aspx page you need to tell the form that it will be using files. I don't think its required but its good practice to also include an id in your input that matches your name.
<body>
<form id="form1" runat="server" method="post" enctype="multipart/form-data">
<input type="file" id="image" name="image" class="image-upload" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</form>
</body>

I'd recommend going with the asp.net file upload control:
<asp:FileUpload ID="pictureUpload" class="form-control input-sm input-spacing" runat="server" />
You can create these dynamically
FileUpload OneUpload = new FileUpload();
OneUpload.ID = "Upload" + MyIdNumber;
UploadsDiv.Controls.Add(OneUpload);
Then to access the file, you have:
pictureUpload.SaveAs(FilePathAndName);
You can also access different properties of the posted file...
pictureUpload.PostedFile.FileName
pictureUpload.PostedFile.ContentLength
pictureUpload.PostedFile.ContentType

Related

Update textbox in UserControl from another UserControl

I hava a MasterPage with 2 UserControls. When something happens in UserControl1.ascx, it has to update a TextBox in UserControl2.ascx.
I tried this inside UserControl1.ascx, but no success:
UserControl userControl = (UserControl)LoadControl("UserControl2.ascx");
var txt = (TextBox) userControl.FindControl("txtTest");
txt.Text = "Hello world";
Thanks for all help :)
The LoadControl is load a new control that is not exist on page...
Lets see this example.
You have a master page that has 2 User Controls.
<form id="form1" runat="server">
<div>
<uc1:WebUserControl ID="WebUserControl1" runat="server" />
<br /><br />
<uc2:WebUserControl ID="WebUserControl2" runat="server" />
<br /><br />
<asp:Button runat="server" ID="btnOk" Text="ok" OnClick="btnOk_Click" />
</div>
</form>
and on code behind this
protected void btnOk_Click(object sender, EventArgs e)
{
WebUserControl1.TextOnMe = WebUserControl2.TextOnMe;
}
Now the user controls have this on html
<asp:TextBox runat="server" ID="txtText"></asp:TextBox>
and on code behind you get and set the Text like that on code behind
public string TextOnMe
{
get
{
return txtText.Text;
}
set
{
txtText.Text = value;
}
}
One Similar Answer
ASP.NET MasterPage only control?

Get html value on Web User Control without runat="server"

I'm new to this world.
As you can see in the picture. This is my Default.aspx page where I have implemented a Web User Control(uc) called "adress.ascx".
My uc control is divided in 2 categories, first is Asp.net controls category and second is Html Controls category.
What is the scenario: I want to copy the value from Html Textbox to Asp:TextBox.
I have 2 options, either I can do with asp:Button or with html button(without runat="server")
Here is my code
<h1>ASP.NET Controls</h1>
<br />
<asp:Label runat="server" Text="Street"></asp:Label>
<asp:TextBox runat="server" ID="tbStreet" Text=""></asp:TextBox><br /><br />
<asp:Button ID="btnAsp" Text="Button ASP" runat="server"
OnClick="btnAsp_Click"
/>
<h2>-------------------------------</h2>
<h1>Html Controls</h1>
Street
<input type="text" name="Street" id="street"><br />
<br />
<button type="button" id="btnStreet">Button HTML!</button>
And here is my code "code behind" in c#
protected void btnAsp_Click(object sender, EventArgs e)
{
string value = Request.Form["street"];
}
When I run this code, the value I get is null
I hope you will find this helpful .
**Aspx Page**
<input type='button' id='btnAsp1' value='Shop Now' class='form-control'
value='Button:1' onclick='javascript:__doPostBack("btnAsp1");'
style='background-color:#3465aa; color:white' >
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
**Code Behind**
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["__EVENTTARGET"] != null &&
Request.Form["__EVENTTARGET"] == "btnAsp1")
{
btnAsp1_Click(null, null);
}
}
private void btnAsp1_Click(object sender, System.EventArgs e)
{
Response.Write("You Clicked on " +
Request.Form["__EVENTARGUMENT"].ToString());
}
Here is the solution.
Code for Defualt.aspx page.
<%# Register Src="~/WebUserControl.ascx" TagName="Add" TagPrefix="uc1"
%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<uc1:Add runat="server" ID="ucAdres" WidthFirstCollumn="175px" />
</body>
</html>
And here is the code for WebUserControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<form method="post" runat="server"
>
<h1>ASP.NET Controls</h1>
<br />
<asp:Label runat="server" Text="Street" ID="lable"></asp:Label>
<asp:TextBox runat="server" ID="tbStreet" Text="Text Asp.net text box"></asp:TextBox><br />
<br />
<asp:Button ID="btnAsp" runat="server" Text="Button Asp.net" OnClick="btnAsp_Click"/><br />
<input type="submit" id="btnHtml" value="Html Button" />
<h2>-------------------------------</h2>
<h1>Html Controls</h1>
Street
<input type="text" name="street" id="street" value="Text coming from HTML5"">
<br />
<br />
<button type="button" id="btnStreet">Button HTML!</button>
</form>
And here is the code of WebUserControl.ascx.cs
protected void btnAsp_Click(object sender, EventArgs e)
{
string value = Page.Request.Form["street"].ToString();
if (value != null)
{
tbStreet.Text = value;
} else
{
tbStreet.Text = "Nooooooooo";
}
}
I explain again, that you have a WebUserControl where you have 2 types of Controls(Asp.net and html). What you want to do is to copy from HTML to asp.net without runat="server".
I often has problem of Form so finally I found that I have 2 Forms, 1 on WebUserControl and 1 on Default.aspx.
Your screenshot shows a breakpoint on the following line:
string value = Request.Form["street"];
with value being null. However, from Using Breakpoints on MSDN (emphasis mine):
When you run this code in the debugger, execution stops whenever the breakpoint is hit, before the code on that line is executed
If you go to the next line, the line will run and populate value. To copy this into the ASP.net control, the following should be sufficient:
protected void btnAsp_Click(object sender, EventArgs e)
{
tbStreet.Text = Request.Form["street"];
}
I would caution that what you are trying to do probably has a better solution, so even if this solves your immediate problem you may find that other issues crop up further down the line.

How to display image after selecting path in FileUpload controller without clicking

Recently I have been developing web form application in ASP.NET (c#):
I have an Image control:
<asp:Image ID="Avatar" runat="server" Height="225px" ImageUrl="~/Images/NoUser.jpg" Width="225px" />
And FileUpload & Button control
<asp:FileUpload ID="avatarUpload" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
When user click button then "Upload" code is executed (the image is sent to the database). Problem is that I like to display the image which the user selected in Avatar Image controller before the user clicks "desperate" button.
Is that possible to do this automatically?
With the help of File Api of HTML5 (Example: Using files from web applications) you can accomplish this easily. Change the markup to use input type="file" instead of asp:FileUpload and add ID, add tag runat="server" to make it accessible from server. Your markup should look like:
<input ID="avatarUpload" type="file" name="file" onchange="previewFile()" runat="server" />
<%--<asp:FileUpload ID="avatarUpload" runat="server" />--%>
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<asp:Image ID="Avatar" runat="server" Height="225px" ImageUrl="~/Images/NoUser.jpg" Width="225px" />
Now add a javascript function previewFile in the head of document:
<head runat="server">
<title></title>
<script type="text/javascript">
function previewFile() {
var preview = document.querySelector('#<%=Avatar.ClientID %>');
var file = document.querySelector('#<%=avatarUpload.ClientID %>').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
</script>
</head>
Now after selecting an image you can see the preview like below:
You can use css to re-size it to a thumbnail.
After clicking the Upload button, in the code you can find the posted file:
protected void Upload(object sender, EventArgs e)
{
int contentLength = avatarUpload.PostedFile.ContentLength;//You may need it for validation
string contentType = avatarUpload.PostedFile.ContentType;//You may need it for validation
string fileName = avatarUpload.PostedFile.FileName;
avatarUpload.PostedFile.SaveAs(#"c:\test.tmp");//Or code to save in the DataBase.
}

How to create onclick event in .cs file for html <Input> Tag?

How to create onclick event in .cs file for asp.net c# for html Tag ?
Example :-
< input type="button" id="btnBeforeOk" value="Ok" name="btnBeforeOk" style="width: 90%;" />
I want to create an event in .cs file how we can do this ?
OR
bool isEmail = Regex.IsMatch("nikunj#yahoo.com", #"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|asia|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel)\b)\Z", RegexOptions.IgnoreCase);
The above bool isEmail i want to in .aspx page ?
Very simple.
HTML:
<input type="button" id="btnBeforeOk" value="Ok" runat="server" name="btnBeforeOk" style="width: 90%;" />
Now go to HTML view of your page and double click on your button, it will generate event for you and button markup will be changed to below:
<input type="button" id="btnBeforeOk" value="Ok" runat="server" name="btnBeforeOk" style="width: 90%;" onserverclick="btnBeforeOk_ServerClick" />
and you can find below event in your code behind:
protected void btnBeforeOk_ServerClick(object sender, EventArgs e)
{
Response.Write("hello");
}
I hope it helps!
I think you should use :
<asp:Button ID="MyButton" runat="server" OnClick="YourEvent" />
And do whatever you want to do in the code behind :
protected void YourEvent(object sender, EventArgs e)
{
//work
}

upload excel file using ASP.net and C#

How to upload excel file using ASP.net and C#?
Would not be very easy it is ?
<!-- front end -->
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload Excel File"
onclick="btnUpload_Click" />
//backend
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
if (System.IO.Path.GetExtension(FileUpload1.FileName) == ".xls" || System.IO.Path.GetExtension(FileUpload1.FileName) == ".xlsx")
{
FileUpload1.SaveAs(Server.MapPath("~/upload/temp/Forecast.xls"));
}
}
}
In your aspx page you can use the following...make sure you have enctype="multipart/form-data" in your form tag it will allow the posting of files.
<form enctype="multipart/form-data">
<input type="file" id="excel-file" name="excel-file" />
<input type="submit" />
</form>
Getting the file from the form post...
protected void Page_Load(object sender, EventArgs e)
{
if(this.IsPostback)
{
var yourFile = this.Request.Files["excel-file"];
}
}
I use This
It works perfectly, without anything needed to be changed in the code.

Categories

Resources