Asp.net Multiple File Uploads - c#

I have an ASP.net web application which saves all details entered in the session and at the end, sends an email with all the details including an attachment of the file uploaded (all this currently works fine).
The issue I have is that a change is required to the file upload page. I want to now be able to upload multiple docs, but separately, so basically the user finds the file to upload then clicks an 'Add' button. The upload file field should then clear and a table should populate with the uploaded file(s) with a 'Remove/Delete' button for each file uploaded.
The details that should be displayed in this table are:
File name
Option selected form the new dropdown list
Remove button
As I said I have single file upload working using the code behind but I have no idea how to implement what I'm after so that all uploaded doc's are sent in my email.
Current HTML
<div class="form-group">
<div class="col-sm-offset-2 col-sm-5">
<div class="fileinput fileinput-new input-group" data-provides="fileinput">
<div class="form-control" data-trigger="fileinput" style="background-color: #ededed">
<span class="fileinput-filename"></span>
</div>
<span class="input-group-addon btn btn-default btn-file">
<span class="fileinput-new">
<span class="glyphicon glyphicon-folder-open" title="Click to select a file."></span>
</span>
<span class="fileinput-exists">
<span class="glyphicon glyphicon-folder-open" title="Click to change the selected file."></span>
</span>
<input type="file" name="..." id="fuAttachment" runat="server" />
</span>
</div>
</div>
<div class="col-sm-3">
<asp:DropDownList ID="Step03WebTypeDD" runat="server" class="form-control">
<asp:ListItem Value="- - Please select - -">- - Please select - -</asp:ListItem>
<asp:ListItem Value="Requirements">Requirements</asp:ListItem>
<asp:ListItem Value="Functional specification">Functional specification</asp:ListItem>
<asp:ListItem Value="Page Content">Page Content</asp:ListItem>
<asp:ListItem Value="Page Designs">Page Designs</asp:ListItem>
<asp:ListItem Value="Page Designs">Other</asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-sm-1">
<asp:LinkButton ID="UploadAddButton" runat="server" OnClick="Step05UploadAddButton_Click" CssClass="btn btn-success pull-right" ToolTip="Click to upload the file.">
<span class="glyphicon glyphicon-plus"></span> Add
</asp:LinkButton>
</div>
</div>
Current Code Behind
protected void Step05UploadAddButton_Click(object sender, EventArgs e)
{
var file = fuAttachment.PostedFile;
if (file != null && fuAttachment.PostedFile.FileName != "")
{
var content = new byte[file.ContentLength];
file.InputStream.Read(content, 0, content.Length);
Session["FileContent"] = content;
Session["FileContentType"] = file.ContentType;
Session["File"] = fuAttachment.PostedFile.FileName;
Session["AttachmentProvided"] = "Yes";
}
else
{
Session["FileContent"] = "";
Session["FileContentType"] = "";
Session["File"] = "";
Session["AttachmentProvided"] = "No";
}
}
My code behind does not capture the option selected but will need to so I can display it on my confirmation page (HTML shown below)
<div class="form-group">
<asp:Label ID="Label6" class="col-xs-6 col-sm-3 control-label" runat="server" Text="Attachment provided:"></asp:Label>
<div class="col-xs-6 col-sm-9 form-control-static">
<% if (Session["AttachmentProvided"] == "Yes")
{%>
Yes (<%=Session["File"] %>)
<%}
else
{ %>
No
<%} %>
</div>
</div>

You can use JavaScript to add additional <input type="file" /> elements to the DOM, and generically refer to all of the files using Request.Files as mentioned on MSDN. A sample taken from MSDN:
Files = Request.Files; // Load File collection into HttpFileCollection variable.
arr1 = Files.AllKeys; // This will get names of all files into a string array.
for (loop1 = 0; loop1 < arr1.Length; loop1++)
{
Response.Write("File: " + Server.HtmlEncode(arr1[loop1]) + "<br />");
Response.Write(" size = " + Files[loop1].ContentLength + "<br />");
Response.Write(" content type = " + Files[loop1].ContentType + "<br />");
}

Related

Passing parameters beetween .aspx and .aspx.cs

I am using Visual Studio 2015 Ultimate. I have put a raw HTML web form in my Test.aspx file and want to pass the parameters of form-fields (like : Username, password, mobile no. etc.) from Test.aspx to Test.aspx.cs file. Although, I have written the code for passing the values in the button click function, I can't get the data. I have written "string u = Request.QueryString["username"];" for username field (without quotes) and so on and another line to print the value in that form itself, that is "Response.Write(u);" (without quotes). Here, I can't see the printed values in my form. How can I solve this issue?
Register.aspx file-
<!-- Start Register Section -->
<div id="login-page">
<div class="layer-stretch">
<div class="layer-wrapper">
<div class="layer-container">
<form class="form-container" action="Register.aspx" method="post" enctype="multipart/form-data" runat="server">
<input type="hidden" name="_token" value="15276e55e6cdfa6911f440f75f64501dc97cc6f4a19102dddb4c47f0c4dd1523ad639943996afef209d6a358056f3b3389a9bcb175b7413ef3547589673a2b7d">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-user-o"></i>
<input class="mdl-textfield__input" type="text" name="fullname" pattern="[A-Z,a-z, ]*" id="register-first-name" runat="server">
<label class="mdl-textfield__label" for="register-first-name">الاسم الكامل<em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال اسم كامل صالح!</span>
</div>
<!--<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-user-o"></i>
<input class="mdl-textfield__input" type="text" name="lastname" pattern="[A-Z,a-z, ]*" id="register-last-name">
<label class="mdl-textfield__label" for="register-last-name">الكنية <em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال الاسم الصحيح!</span>
</div>-->
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-envelope-o"></i>
<input class="mdl-textfield__input" type="text" name="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" id="register-email" runat="server">
<label class="mdl-textfield__label" for="register-email">البريد الإلكتروني <em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال بريد إلكتروني صحيح!</span>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-phone"></i>
<input class="mdl-textfield__input" type="text" name="mobile" pattern="[0-9]*" id="register-mobile" runat="server">
<label class="mdl-textfield__label" for="register-mobile">رقم الهاتف المحمول <em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال رقم الجوال صحيح!</span>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-key"></i>
<input class="mdl-textfield__input" type="password" name="password" id="register-password" runat="server">
<label class="mdl-textfield__label" for="register-password">كلمه السر <em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال كلمة المرور صالحة (الحد الأدنى 6 حرف)!</span>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon">
<i class="fa fa-key"></i>
<input class="mdl-textfield__input" type="password" name="confirmpassword" id="register-confirm-password" runat="server">
<label class="mdl-textfield__label" for="register-confirm-password">تأكيد كلمة المرور <em> *</em></label>
<span class="mdl-textfield__error">الرجاء إدخال تأكيد كلمة المرور (الحد الأدنى 6 حرف)!</span>
</div>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label form-input-icon form-bot-check">
<i class="fa fa-question"></i>
<input class="mdl-textfield__input" type="number" name="bot-check" id="register-bot" runat="server">
<label class="mdl-textfield__label" for="register-bot">ما هو 10 زائد 3 =<em>* </em></label>
<span class="mdl-textfield__error">الرجاء إدخال القيمة الصحيحة!</span>
</div>
<!--<div class="login-condition">بالنقر على "إنشاء حساب" فإنك توافق على موقعنا<br />شروط & الظروف</div>-->
<div class="form-submit">
<!-- <button class="mdl-button mdl-js-button mdl-js-ripple-effect button button-primary" name="register" onclick="Submit_Click">إصنع حساب</button>-->
<asp:Button ID="Button1" runat="server" OnClick="Submit_Click" Text="Submit" class="mdl-button mdl-js-button mdl-js-ripple-effect button button-primary" />
<asp:Button ID="Button2" runat="server" Text="Register" class="mdl-button mdl-js-button mdl-js-ripple-effect button button-primary" OnClick="Button2_Click" />
</div>
<div class="login-link">
<span class="paragraph-small">هل لديك حساب؟</span>
تسجيل الدخول
</div>
</form>
</div>
</div>
</div>
</div>
<!-- End Register Section -->
Register.aspx.cs file-
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MDC_web {
public partial class Register: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
}
protected void Submit_Click(object sender, EventArgs e) {
System.Diagnostics.Debug.WriteLine("Register button has been clicked!!");
string fn = String.Format("{0}", Request.Form["fullname"]);
Response.Write("<script language='JavaScript'> alert('jhkjhjk');</script>");
Response.Write(fn);
string em = Request.QueryString["email"];
Response.Write(em);
string mob = Request.QueryString["mobile"];
Response.Write(mob);
string p = Request.QueryString["password"];
string cp = Request.QueryString["confirmpassword"];
/*if (p.Equals(cp))
{
string c = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
SqlConnection con = new SqlConnection(c);
con.Open();
SqlCommand cmd = new SqlCommand("insert into Register (R_Name, Email, Mobile, R_Pass) values ('" + fn + "','" + em + "'," + mob + ",'" + p + "')", con);
int r = cmd.ExecuteNonQuery();
if (r == 1)
{
Response.Write("<script language='JavaScript'> alert('Registration is successfull!!');</script>");
}
}*/
}
/*protected void Button2_Click(object sender, EventArgs e)
{
Response.Write("<script language='JavaScript'> alert('jhkjhjk');</script>");
//Response.Write(fn);
}*/
}
}
for use form-fields values in .cs you have to do targetting like this
string Username = txtUsername.Value.Trim(); (txtUsername is the name of field in aspx)
string Password = txtPassword.Value.Trim();
string Mobile = txtMobile.Value.Trim();
the query string is used for passing value trough aspx pages not for aspx to cs
You can access asp id from the .aspx in your .aspx.cs.
just give them a unique ID and runat like so:
.aspx
<asp:TextBox runat="server" ID="txtUsername"></asp:TextBox>
.aspx.cs
var username = txtUsername.Text;
this is for receiving the text of the textbox. If you want to set the text then simply change it to txtusername.Text = "test test". You can to this also with asp:labels, asp:button etc.
Check this post for more informations
If you want to do that on a button click just make use of the postback which happens after the click.
.aspx
<asp:TextBox runat="server" ID="txtUsername"></asp:TextBox>
<asp:Button runat="server" ID="btnSumbit" Text="submit"></asp:Button>
.aspx.cs
protected void btnSumbit_Click(object sender, EventArgs e){
var username = txtUsername.Text;
//do username stuff in here
}
if you need a Tutorial for a login form with websforms check one of these:
https://msdn.microsoft.com/en-us/library/ff184050.aspx
https://www.youtube.com/watch?v=QoPABrUknsE
Do not transmit a password, in plain text, via a query string. Set up a https connection for your production site - you can do it free with Let's Encrypt. You say you added a "raw HTML form" - add plain HTML elements but do not add an extra form element because ASPNET can only handle a single form with a runat="server" attribute.
Then, to use plain HTML, just add runat="server" so that you can grab the data on the server side:
Test.aspx:
User Name: <input type="text" name="userName" runat="server">
Test.aspx.cs
string userName = userName.Value.Trim();
UPDATE:
If you're using a master page, why have you got a form tag in the aspx? The master page usually contains the form tag so it looks like you're copying and pasting code from somewhere else. Remove the form tag from your aspx.
Don't pass sensitive information in the URL via a query string. Use a single form tag in your master page, then in your code-behind:
string fName = register-first-name.Value;
You're using ASPNET so there is no point in the pattern attribute. Simply add a Regular Expression validator control.

How to loop div?

I am trying to loop few div's in aspx. This the code I would like to loop:
<div class="col-md-3 product-men">
<div class="men-pro-item simpleCart_shelfItem">
<div class="men-thumb-item">
<img src="uploadImage/3.png" class="pro-image-front" />
<img src="uploadImage/3.png" class="pro-image-back" />
</div>
<div class="item-info-product ">
<h4>Tie Clip</h4>
<div class="info-product-price">
<span class="item_price">RM100</span>
</div>
Add to cart
</div>
</div>
</div>
The page looks like below:
the cart need to loop. I have tried using c# as below:
StringBuilder cart = new StringBuilder();
for (int x = 0; x < 3; x++) {
cart.Append(" <div class=\"col - md - 3 product - men\">");
cart.Append("<div class=\"men - pro - item simpleCart_shelfItem\">");
cart.Append("<div class=\"men - thumb - item\">");
cart.Append("<img src = uploadImage/1.jpg class='pro - image - front />");
cart.Append("<img src = uploadImage/1.jpg class=pro - image - back />");
cart.Append("</div>");
cart.Append(" <div class=\"item - info - product \">");
cart.Append("<h4><a href = \"single.html\" > Tie Clip</a></h4>");
cart.Append("<div class=\"info - product - price\">");
cart.Append("<span class=\"item_price\">RM100</span>");
cart.Append("</div>");
cart.Append("Add to cart");
cart.Append("</div>");
cart.Append("</div>");
cart.Append("</div>");
}
Literal1.Text = cart.ToString();
This don't seem work out.. Any idea how to get this cart loop?
You should use Embedded Code Blocks in the .aspx itself instead of .cs.
You would normally use a asp.net Control for that, like a Repeater.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div class="col-md-3 product-men">
<div class="men-pro-item simpleCart_shelfItem">
<div class="men-thumb-item">
<img src="uploadImage/<%# Eval("product_image_front") %>" class="pro-image-front" />
<img src="uploadImage/<%# Eval("product_image_back") %>" class="pro-image-back" />
</div>
<div class="item-info-product ">
<h4><%# Eval("product_name") %></h4>
<div class="info-product-price">
<span class="item_price"><%# Eval("product_price") %></span>
</div>
<asp:LinkButton ID="LinkButton1" CommandArgument='<%# Eval("product_id") %>' runat="server" CssClass="item_add single-item hvr-outline-out button2">Add to cart</asp:LinkButton>
</div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Then in code behind you would assign a DataSource to the Repeater.
Repeater1.DataSource = source;
Repeater1.DataBind();
Code in aspx Page
<asp:Literal ID="ltrMessage" runat="server"></asp:Literal>
Code Snippet in cs page.
for(int i=0;i<limit;i++)
{
ltrMessage.Text+=#"<div class='col-md-3 product-men'>
<div class='men-pro-item simpleCart_shelfItem'>
<div class='men-thumb-item'>
<img src='uploadImage/3.png' class='pro-image-front' />
<img src='uploadImage/3.png' class='pro-image-back' />
</div>
<div class='item-info-product '>
<h4><a href='single.html'>Tie Clip</a></h4>
<div class=''info-product-price'>
<span class='item_price'>RM100</span>
</div>
<a href='#' class='item_add single-item hvr-outline-out button2'>Add to cart</a>
</div>
</div>
</div>";
}

ASP.net File Upload To Populate A Table But Save All Files In Session

I have an asp.net web application which saves all details entered and at the end sends an email with all the details including file upload functionality (all this works).
The issue I have is that a change is required to the file upload page. I want to now be able to upload multiple docs so basically the user finds the file to upload then clicks an 'Add' button. The upload filed should then clear and a table should populate with the uploaded file(s) witht he action to edit or remove it.
As I said I have single file upload working using the code behind but I have no idea how to implement what I'm after so that all uploaded doc's are sent in my email.
HTML
<div class="form-group">
<div class="col-sm-offset-2 col-sm-5">
<div class="fileinput fileinput-new input-group" data-provides="fileinput">
<div class="form-control" data-trigger="fileinput" style="background-color: #ededed">
<span class="fileinput-filename"></span>
</div>
<span class="input-group-addon btn btn-default btn-file">
<span class="fileinput-new">
<span class="glyphicon glyphicon-folder-open" title="Click to select a file."></span>
</span>
<span class="fileinput-exists">
<span class="glyphicon glyphicon-folder-open" title="Click to change the selected file."></span>
</span>
<input type="file" name="..." id="fuAttachment" runat="server" />
</span>
<a href="#" class="input-group-addon btn btn-default fileinput-exists" data-dismiss="fileinput">
<span class="glyphicon glyphicon-remove" title="Remove selected file."></span>
</a>
</div>
</div>
<div class="col-sm-3">
<asp:DropDownList ID="Step03WebTypeDD" runat="server" class="form-control">
<asp:ListItem Value="- - Please select - -">- - Please select - -</asp:ListItem>
<asp:ListItem Value="Requirements">Requirements</asp:ListItem>
<asp:ListItem Value="Functional specification">Functional specification</asp:ListItem>
<asp:ListItem Value="Page Content">Page Content</asp:ListItem>
<asp:ListItem Value="Page Designs">Page Designs</asp:ListItem>
<asp:ListItem Value="Page Designs">Other</asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-sm-1">
<asp:LinkButton ID="UploadAddButton" runat="server" OnClick="Step05UploadAddButton_Click" CssClass="btn btn-success pull-right" ToolTip="Click to upload the file.">
<span class="glyphicon glyphicon-plus"></span> Add
</asp:LinkButton>
</div>
</div>
Code behind
var file = fuAttachment.PostedFile;
if (file != null && fuAttachment.PostedFile.FileName != "")
{
var content = new byte[file.ContentLength];
file.InputStream.Read(content, 0, content.Length);
Session["FileContent"] = content;
Session["FileContentType"] = file.ContentType;
Session["File"] = fuAttachment.PostedFile.FileName;
Session["AttachmentProvided"] = "Yes";
}
else
{
Session["FileContent"] = "";
Session["FileContentType"] = "";
Session["File"] = "";
Session["AttachmentProvided"] = "No";
}
Just to give you an idea on how to implement it... Store a list of object to your session..
MyFile object:
class MyFile
{
public Guid Id { get; set; }
public byte[] Content { get; set; }
public string ContentType { get; set; }
public string Name { get; set; }
public MyFile()
{
Id = Guid.NewGuid();
}
}
UPDATE: Added view code
View:
<asp:ListView ID="uploadedFileList" runat="server">
<ItemTemplate>
<tr>
<td><%# Eval("Name")%></td>
<td><%# Eval("ContentType")%></td>
<td><asp:LinkButton Text="Remove" ID="lkbCommandAction" CommandArgument='<%# Eval("Id") %>' OnCommand="lkbCommandAction_Command" runat="server" /></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="tbl1" runat="server">
<tr id="tr1" runat="server">
<td id="td1" runat="server">File Name</td>
<td id="td2" runat="server">Content-Type</td>
<td id="td3" runat="server"></td>
</tr>
<tr id="ItemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
Code Behind:
var file = fuAttachment.PostedFile;
if (file != null && fuAttachment.PostedFile.FileName != "")
{
var content = new byte[file.ContentLength];
file.InputStream.Read(content, 0, content.Length);
List<MyFile> myUploadedFiles = null;
if(Session["UploadedFiles"] == null)
{
myUploadedFiles = new List<MyFile>();
}
else
{
myUploadedFiles = (List<MyFile>)Session["UploadedFiles"];
}
myUploadedFiles.Add(new MyFile()
{
Content = content,
ContentType = file.ContentType,
Name = file.FileName
});
Session["UploadedFiles"] = myUploadedFiles;
}
else
{
Session["UploadedFiles"] = null;
}
uploadedFileList.DataSource = myUploadedFiles;
uploadedFileList.DataBind();
protected void lkbCommandAction_Command(object sender, CommandEventArgs e)
{
if (e.CommandArgument == null)
{
/*TODO*/
}
else
{
List<MyFile> myUploadedFiles = null;
if(Session["UploadedFiles"] == null)
{
myUploadedFiles = new List<MyFile>();
}
else
{
myUploadedFiles = (List<MyFile>)Session["UploadedFiles"];
}
Guid removeId= (Guid)e.CommandArgument;
MyFile fileToRemove = myUploadedFiles.FIrstOrDefault(ff => ff.Id == removeId);
if(fileToRemove != null)
{
myUploadedFiles.Remove(fileToRemove);
}
uploadedFileList.DataSource = myUploadedFiles;
uploadedFileList.DataBind();
}
}
Since you now have a list of files in your session you can track the file names, content type, etc. of the uploaded files by the user and do what you want with them.

Show product details in page

I need to show products details in a page.
My aspx is like below...
<div class="col-xs-12 col-sm-4 no-margin product-item-holder hover"> <!-- this div will be repeated for each product -->
<div class="product-item">
<div class="image">
<img runat="server" id="img" alt="" src="" />
</div>
<div class="body">
<div class="label-discount clear"></div>
<div class="title">
<a runat="server" id="name" href="single-product.html"></a>
</div>
</div>
<div class="prices">
<div class="price-prev"></div>
<div runat="server" id="price" class="price-current pull-right"></div>
</div>
<div class="hover-area">
<div class="add-cart-button">
Enquiry
</div>
</div>
</div>
and my codebehind is like below...
dbConnection cn = new dbConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getLoopData();
}
}
public void getLoopData()
{
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select * FROM products";
MySqlDataReader reader = cn.cmd.ExecuteReader();
while (reader.Read())
{
//int id = reader.GetInt32(0);
name.InnerText = reader["InventionName"].ToString();
price.InnerText = reader["Price"].ToString();
img.Src = reader["Picture"].ToString();
}
reader.Close();
cn.con.Close();
}
But it is showing only last product details.
How should I repeat the div for each product and how to show every products in page ??
You can use Asp Repeater to do that.
Check this link out : http://www.w3schools.com/aspnet/aspnet_repeater.asp
You need a datagrid control, repeater or similar to show tabular data.
Right now you only have one control per attribute to show all records, that's why last one wins.
Your view/page could be like this:
<asp:Repeater ID="ProductRepeater" runat="server" EnableViewState="False">
<ItemTemplate>
<div class="product-item">
<div class="image">
<img id="img" alt="" src='<%# Eval("Picture") %>' />
///...
</ItemTemplate>
</asp:Repeater>
In your code you could do this:
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "SELECT InventionName, Price, Picture FROM products";
MySqlDataReader reader = cn.cmd.ExecuteReader();
ProductRepeater.DataSource = reader;
ProductRepeater.DataBind();
You are iterating a list, and assigning data to name, price and img.Src, but you overwrite the values on each iteration, therefore you only have the values from the last element.
You should bind you data source (reader) to an <asp:Repeater>'s DataSource property. In your markup you specify a header (HeaderTemplate), a footer (FooterTemplate) and content (ItemTemplate). You can omit the header and footer template if you don't need them. You can also use an AlternatingItemTemplate if you need to do different things with odd/even rows (e.g. alternating row color in a table).
You can access properties of the databound datatype using the <%# Eval("SomeProperty") %> which is a databinding expression.
HTML markup would be something like this:
<asp:Repeater id="Products" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<div class="col-xs-12 col-sm-4 no-margin product-item-holder hover"> <!-- this div will be repeated for each product -->
<div class="product-item">
<div class="image">
<img class="img" alt="" src="<%# Eval("Picture") %>" />
</div>
<div class="body">
<div class="label-discount clear"></div>
<div class="title">
<a class="name" href="single-product.html"><%# Eval("InventionName") %></a>
</div>
</div>
<div class="prices">
<div class="price-prev"></div>
<div class="price" class="price-current pull-right"><%# Eval("Price") %></div>
</div>
<div class="hover-area">
<div class="add-cart-button">
Enquiry
</div>
</div>
</div>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
and wire up the datasource in codebehind like this:
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select * FROM products";
MySqlDataReader reader = cn.cmd.ExecuteReader();
Products.DataSource = reader; // rather than iterating manually, you assign the datasource to the repeater.
Products.DataBind();
reader.Close();
cn.con.Close();
Side note: I changed the attribute from id to class on the name, price and img element. Because when this markup is rendered it would have been with multiple elements with the same id, which it shouldn't since id is supposed to be unique according to specification.

Email Attachment No Longer Working As Custom Styled ASP:FileUpload Field

I have an asp.net application which allows a file upload and I had this working correctly but now I have custom styled my file upload field it's no longer working and I can't figure out how to get it working again with my new styled field.
OLD HTML
<div class="form-group">
<asp:Label ID="Label3" class="col-md-3 control-label" runat="server" Text="Upload"></asp:Label>
<div class="col-md-3">
<asp:FileUpload ID="fuAttachment" runat="server" class="fileupload"></asp:FileUpload>
</div>
</div>
OLD Code Behind
var file = fuAttachment.PostedFile;
if (file != null && fuAttachment.PostedFile.FileName != "")
{
var content = new byte[file.ContentLength];
file.InputStream.Read(content, 0, content.Length);
Session["FileContent"] = content;
Session["FileContentType"] = file.ContentType;
Session["File"] = fuAttachment.FileName;
Session["AttachmentProvided"] = "Yes";
}
NEW HTML
<div class="fileinput fileinput-new input-group" data-provides="fileinput">
<div class="form-control" data-trigger="fileinput" style="background-color: #ededed">
<span class="fileinput-filename"></span>
</div>
<span class="input-group-addon btn btn-default btn-file">
<span class="fileinput-new">
<span class="glyphicon glyphicon-folder-open" title="Click to select a file."></span>
</span>
<span class="fileinput-exists">
<span class="glyphicon glyphicon-folder-open" title="Click to change the selected file."></span>
</span>
<input type="file" name="...">
</span>
<a href="#" class="input-group-addon btn btn-default fileinput-exists" data-dismiss="fileinput">
<span class="glyphicon glyphicon-remove" title="Remove selected file."></span>
</a>
</div>
I need to store in my session as this populates another page so I need similar code behind as I had
Edit file input to :
<input type="file" id="fuAttachment" runat="server" />
Now you use fuAttachment from codebehind for access uploaded file.
Note: If runat="server" attribute is missing you don't able to control this input from codebehind.

Categories