ASP.NET check which button was clicked - c#

Here's the deal, I making a website that sells some products and according to how much products I have the ammount of buttons changes too.
For example if I have 5 products I will have 5 buttons, something like this:
What I want to do is when a button is clicked I want to take the item name and save it (in a session) so I can use this information on a different page (the code behind is in C#).
How can I do this?
Html:
<div runat="server" id="CatalogProducts" class="container-fluid">
</div>
Code behind:
SqlHey SQLViewProducts = new SqlHey();
DataSet DSViewProducts = new DataSet();
string Sheilta = "SELECT TblShop.ItemName, TblShop.Price, TblShop.ShopType, TblShop.Image, TblShop.Description FROM TblShop;";
DSViewProducts = SQLViewProducts.chkData(Sheilta);
int I;
for (I = 0; I < DSViewProducts.Tables[0].Rows.Count; I++)
{
if (DSViewProducts.Tables[0].Rows.Count % 2 == 0)
{
if (I % 2 == 0)
CatalogProducts.InnerHtml += " <div class=\"row\"> <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div>";
else CatalogProducts.InnerHtml += " <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div> </div> <br /> <br />";
}
if (DSViewProducts.Tables[0].Rows.Count % 2 != 0)
{
if (I + 1 == DSViewProducts.Tables[0].Rows.Count)
CatalogProducts.InnerHtml += " <div class=\"row\"> <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div>";
if (I % 2 == 0)
CatalogProducts.InnerHtml += " <div class=\"row\"> <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div> </div> <br /> <br />";
else CatalogProducts.InnerHtml += " <div style=\"position: relative\" class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 col-sm-push-1 animated bounceInLeft\"> <div class=\"hovereffect\"> <img class=\"img-responsive\" src= \".." + DSViewProducts.Tables[0].Rows[I][3].ToString() + "\"" + " alt=\"\"> <div class=\"overlay\"> <h2>הוסף<span style=\"font-size: 0.65em\"></span> <asp:Button ID=\"Button1\" runat=\"server\" BackColor=\"Transparent\" BorderStyle=\"None\" ForeColor=\"Transparent\" Height=\"43px\" Style=Height=\"z-index: 99; left: 0px; position: absolute; top: 0px\" Text=\"a\" Width=\"87px\" />לסל</h2> <p class=\"icon-links\">" + DSViewProducts.Tables[0].Rows[I][0].ToString() + "<br /> " + DSViewProducts.Tables[0].Rows[I][4].ToString() + " </p> </div> </div> </div> </div> <br /> <br />";
}
}
The methood chkData:
public DataSet chkData(string sqlstr)
{
string path = HttpContext.Current.Server.MapPath("~/App_Data/");
string fileName = "Hey.mdb";
path += fileName;
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + path;
OleDbConnection conn = new OleDbConnection(connString);
OleDbDataAdapter da = new OleDbDataAdapter(sqlstr, conn);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}

In the CatalogProducts.InnerHtml bind the for loop count to button ID,if not possible to bind then try instead of asp button you may use input type="button"
I just added to your code refer this..
<input type="Button" id=\"Button_\"+I />

It's better to use Repeater for this solution. Check out this link. It will tell you what to do step by step.

Related

Dynamic Input Field with .net mvc

I want to add a dynamic input field in my website like this.
Initial state of the form:
Form state after adding first row
Form state after adding second row
How can I do this?
You can use jQuery append method to add row into the table body. but you should follow the name of your elements in the row like
var index = 1 // i assume "0" is used in your first row.
var newRow ="<tr> <td> <input type="text" name="MyListItem[indx].FirstProperty" /><td></tr>";
index++;
$('#tblBody').append(newRow);
This will help your model binding works properly
I will show you my methot. This will help you complately. Just examine carefully.
!!Do not be intimidated by the density of the code, I making many work in page.
I create a partial view for inputs;
<ul class="list-group shadow">
<li class="list-group-item list-group-item-success">
<label class="font-weight-bold">Satış Tipi:</label>
<span class="float-right">
#Html.DropDownList("NewSaleTypeId", null, new { #class = "form-control select2", placeholder = "...Satış Tipi Seçiniz..." })
</span>
</li>
<li class="list-group-item list-group-item-success" id="row_range">
<label class="font-weight-bold">Ürün Gamı:</label>
<span class="float-right">
#Html.DropDownList("NewProductRangeId", null, new { #class = "form-control select2", placeholder = "...Ürün Gamı..." })
</span>
</li>
<li class="list-group-item list-group-item-success" id="NewProductTypeId_row">
<label class="font-weight-bold">Çeşit:</label>
<span class="float-right">
#Html.DropDownList("NewProductTypeId", null, new { #class = "form-control select2", placeholder = "...Çeşit..." })
</span>
</li>
<li class="list-group list-group-item-success" id="NewProductSizeId_row">
<div class="list-group-item list-group-item-success">
<label class="font-weight-bold">Boy:</label>
<span class="float-right">
#Html.DropDownList("NewProductSizeId", null, new { #class = "form-control select2", placeholder = "...Boy..." })
</span>
</div>
<div class="list-group-item list-group-item-success">
<label class="font-weight-bold">İlaç:</label>
<span class="float-right">
#Html.DropDownList("NewProductMedicineId", null, new { #class = "form-control select2", placeholder = "...İlaç..." })
</span>
</div>
</li>
#*<li class="list-group-item list-group-item-success" id="NewProductMedicineId_row">
</li>*#
<li class="list-group-item list-group-item-success">
<label class="font-weight-bold">Açıklama:</label>
<span class="float-right">
#Html.TextBox("NewProductDescription", "", new { #class = "form-control" })
</span>
</li>
<li class="list-group-item list-group-item-success">
<label class="font-weight-bold">Fiyat:</label>
<span class="float-right">
#Html.TextBox("NewUnitPrice", "", new { #class = "form-control" , #type = "number", #min = "1" })
</span>
</li>
<li class="list-group-item list-group-item-success">
<label class="font-weight-bold">Adet:</label>
<span class="float-right">
#Html.TextBox("NewQuantity", "", new { #class = "form-control", #type = "number", #min = "1"})
</span>
</li>
<li class="list-group-item">
<button type="button" class="btn btn-block btn-primary" onclick="addNewProduct()"><i class="fa fa-plus"></i> EKLE</button>
</li>
</ul>
Then I take values with this script;
function addNewProduct() {
var isExists;
var newProductId = $("#NewProductId").val();
var newProductRangeId = $("#NewProductRangeId").val();
var newProductTypeId = $("#NewProductTypeId").val();
var newProductSizeId = $("#NewProductSizeId").val();
var newProductMedicineId = $("#NewProductMedicineId").val();
var newSaleTypeId = $("#NewSaleTypeId").val();
var newProductName = $("#NewProductId option:selected").text();
var newProductRangeName = $("#NewProductRangeId option:selected").text();
var newProductTypeName = $("#NewProductTypeId option:selected").text();
var newSaleTypeName = $("#NewSaleTypeId option:selected").text();
var newProductSizeName = $("#NewProductSizeId option:selected").text();
var newProductMedicineName = $("#NewProductMedicineId option:selected").text();
var newUnitPrice = $("#NewUnitPrice").val();
$("#NewUnitPrice").val("");
var newQuantity = $("#NewQuantity").val();
$("#NewQuantity").val("");
var totalPrice = newQuantity * newUnitPrice;
var newProductDescription = $("#NewProductDescription").val();
$("#NewProductDescription").val("");
if (!newSaleTypeId || !newProductRangeName || totalPrice <= 0 || !newProductTypeName || !newQuantity || !newUnitPrice || (document.getElementById("NewProductSizeId").length > 1 && !newProductSizeName) || document.getElementById("NewProductSizeId").length > 1 && (document.getElementById("NewProductMedicineId").length > 1 && !newProductMedicineName)) {
alert("Bilgileri eksik veya hatalı girdiniz!");
return;
}
var html = "<div class='col-md-3 mb-2'><ul class='list-group shadow border-success border'>" +
//"<li class='list-group-item'><input type='hidden' name='NewProductIds' value='" + newProductId + "'>" + newProductName + "</span></li>" +
"<li class='list-group-item'><input type='hidden' name='NewSaleTypeIds' value='" + newSaleTypeId + "'><label class='font-weight-bold' > Satış Tipi:</label ><span class='float-right'>" + newSaleTypeName + "</span></li>" +
"<li class='list-group-item'><input type='hidden' name='NewProductRangeIds' value='" + newProductRangeId + "'><label class='font-weight-bold' > Ürün Gamı:</label ><span class='float-right'>" + newProductRangeName + "</span></li>" +
"<li class='list-group-item'><input type='hidden' name='NewProductTypeIds' value='" + newProductTypeId + "'><label class='font-weight-bold' > Çeşit:</label ><span class='float-right'>" + newProductTypeName + "</span></li>";
html += newProductSizeId ? "<li class='list-group-item'><input type='hidden' name='NewProductSizeIds' value='" + newProductSizeId + "'><label class='font-weight-bold'> Boy:</label > <span class='float-right'>" + newProductSizeName + "</span></li>" : "<input type='hidden' name='NewProductSizeIds'>";
html += newProductMedicineId ? "<li class='list-group-item'><input type='hidden' name='NewProductMedicineIds' value='" + newProductMedicineId + "'><label class='font-weight-bold'> İlaç:</label ><span class='float-right'>" + newProductMedicineName + "</span></li>" : "<input type='hidden' name='NewProductMedicineIds'>";
html+= "<li class='list-group-item'><label class='font-weight-bold' > Açıklama:</label ><span class='float-right'><input type='text' name='NewProductDescriptions' class='form-control' value='" + newProductDescription + "'></span></li>" +
"<li class='list-group-item'><label class='font-weight-bold' > Fiyat:</label ><span class='float-right'><input type='text' name='NewProductPrices' class='form-control' readonly value='" + newUnitPrice + "'></span></li>" +
"<li class='list-group-item'><label class='font-weight-bold' > Adet:</label ><span class='float-right'><input type='text' name='NewProductQuantities' class='form-control' readonly value='" + newQuantity + "'></span></li>" +
"<li class='list-group-item'><label class='font-weight-bold' > Toplam:</label ><span class='float-right'>"+ totalPrice + " TL</span></li>" +
"<li class='list-group-item'><button type='button' class='btn btn-sm btn-danger' onclick='removeRow(this)'><i class='fa fa-trash'></i> Sil</button></li>" +
"</ul></div>";
$("#salesProducList").append($(html));
$("#NewProductRangeId").val(null).trigger('change');
$("#NewProductTypeId").html("").val(null).trigger('change');
$("#NewProductSizeId").html("").val(null).trigger('change');
$("#NewProductMedicineId").html("").val(null).trigger('change');
}
and then I append codes this part of script $("#salesProducList").append($(html));
and here is the salesProductlist PartialView;
<div class="row">
<div class="col-md-3 mb-2">
#Html.Partial("_SaleProductCE")
</div>
<div class="col-md-9">
#Html.Partial("_SaleProductList")
</div>
</div>
Use $(id).remove(); for remove added row.

i want to assign global variable into local varibale but i am getting error. ;expected

public string strSubCat = "";
strCategory += #"<li class='dropdown menu-large nav-item'><a href='# class='dropdown-
toggle nav-link' data-toggle='dropdown'>" + dr["Category_name"] +# </a>
<ul class='dropdown-menu megamenu'>
<div class='row'>
"string subcat1 = null;
subcat1 +=strSubCat + #"
</div>
</ul>
</li>";
Miss some double quotes and ";"
Try this : ?
string strSubCat = "";
strCategory += #"<li class='dropdown menu-large nav-item'><a href='# class='dropdown-
toggle nav-link' data-toggle='dropdown'>" + dr["Category_name"] + #" </a>
<ul class='dropdown-menu megamenu'>
<div class='row'>;
";
string subcat1 = null;
subcat1 +=strSubCat + #"
</div>
</ul>
</li>";

feature list out and throw it into the foreach

My requirement is that I must have everything in my list display on the page.
The problem is that, with the code I have, it only displays one thing no matter what it is !
Therefore, I would like to know what is going wrong since it does not show more than a thing forward?
default.aspx.cs
DataClassesDataContext db = new DataClassesDataContext();
List<ForslagOpslag> forslagopslag = db.ForslagOpslags.ToList();
foreach (ForslagOpslag item in forslagopslag)
{
//udskriver tekst på siden.
LabelText.Text = item.text;
}
Default.aspx
<asp:Label ID="LabelText" runat="server"></asp:Label>
It displays only one FORWARD, it does not display the rest.
EIDT:
Default.aspx / html
<asp:Label ID="LabelBrugernavn" runat="server"></asp:Label>
<asp:Literal ID="LiteralLikesOpslag" runat="server"></asp:Literal>
<asp:Literal ID="LiteralDelete" runat="server"></asp:Literal>
<div style="margin-bottom: 5px; clear: both;"></div>
<asp:Label ID="LabelText" runat="server"></asp:Label>
<div style="margin-top: 5px; clear: both;"></div>
<div class="col-md-12">
<hr class="tall" style="margin:7px 0;">
</div>
Default.aspx.cs
List<ForslagOpslag> forslagopslag = db.ForslagOpslags.ToList();
foreach (ForslagOpslag item in forslagopslag)
{
//find ud af likes til forslaget.
var likesFjern = db.ForslagOpslagLikes.Where(a => a.fk_brugerid == Helper.ReturnBrugerId()).Count();
//udskriver fornavn og efternavn
LabelBrugernavn.Text = item.brugere.fornavn + " " + item.brugere.efternavn;
//udskriver tekst på siden.
LabelText.Text = item.text;
//finder ud af om man har synes godt om forslag før.
if (likesFjern >= 1)
{
LiteralLikesOpslag.Text = "<a href='fjernsynesgodtom.aspx?id=" + item.Id + "&brugerid=" + Helper.ReturnBrugerId() + "' class='btn btn-danger btn-xs'>Fjern synes godt om</a>";
}
else if (item.brugere.Id != Helper.ReturnBrugerId())
{
LiteralLikesOpslag.Text = "<a href='SynesGodtOm.aspx?id=" + item.Id + "' class='btn btn-success btn-xs'>Like opslag - " + item.ForslagOpslagLikes.Count() + " synes godt om</a>";
}
else
{
LiteralLikesOpslag.Text = "<p class='label label-lg label-success'>" + item.ForslagOpslagLikes.Count() + " synes godt om</p>";
}
//slet opslag både admin og brugeren selv.
//giver det muligt for admin at kunne slette opslag.
if ((item.fk_brugerid == Helper.ReturnBrugerId() || Helper.BrugerRank(Helper.ReturnBrugerId()) == 1))
{
LiteralDelete.Text = "<a href='slet.aspx?id=" + item.Id + "' class='btn btn-danger btn-xs'>Slet</a>";
}
}
You are always resetting the text of the label so effectively, only the last item is shown.
If you want to display all the items, you need to concatinate them.
foreach (ForslagOpslag item in forslagopslag)
{
//udskriver tekst på siden.
LabelText.Text += item.text;
}
Notice the plus sign, to concatinate the strings.
UPDATE, to render an unordered list:
string list = "<ul>";
foreach (ForslagOpslag item in forslagopslag)
{
//udskriver tekst på siden.
list += "<li>" + item.text + "</li>";
}
list += "</ul>";
placeholder.Controls.Add(new LiteralControl(list));
Then change your .aspx page and remove the label and add this instead:
<asp:PlaceHolder runat="server" ID="placeholder" />
You are resetting the text with each new item, use a StringBuilder to create a the longer string, or an itemrepeater so that you can display more than one item at once
So, with a StringBuilder, you could do it as such:
StringBuilder allText = new StringBuilder();
foreach (ForslagOpslag item in forslagopslag) {
allText.AppendLine(item.text);
}
LabelText.Text = allText.ToString();
or you could use another control like an Repeater to display the full dataset at once, with a template, for example as such:
<asp:Repeater ID="itemRepeater" runat="server">
<ItemTemplate>
<div><asp:Label ID="lblTest" runat="server" Text='<%#Bind("text")%>' /></div>
</ItemTemplate>
</asp:Repeater>
and in your code behind, you could add it to the page load event, as such:
itemRepeater.DataSource = forslagopslag;
itemRepeater.DataBind();
This also allows you to bind to multiple elements, or to define a header template or, just look into the Repeater MSDN help page

Garden label into Repeater to find my label

It is such that I have a Repeater with both label and Literal content, and that is how I got it into Repeater and I would like it being like shown at the side.
It appears with the error that tells me that it can not find my label or Literal
Repeater her:
<asp:Repeater ID="RepeaterOpslag" runat="server">
<ItemTemplate>
<div id="forslagbox" runat="server">
<asp:Label ID="LabelBrugernavn" runat="server"></asp:Label>
<asp:Literal ID="LiteralLikesOpslag" runat="server"></asp:Literal>
<asp:Literal ID="LiteralDelete" runat="server"></asp:Literal>
<div style="margin-bottom: 5px; clear: both;"></div>
<asp:Label ID="LabelText" runat="server"></asp:Label>
<div style="margin-top: 5px; clear: both;"></div>
<div class="col-md-12">
<hr class="tall" style="margin: 7px 0;">
</div>
</div>
</ItemTemplate>
</asp:Repeater>
Default.aspx.cs here, It is in foreach which gives me problems that it will not print any of it at all.
RepeaterOpslag.DataSource = db.ForslagOpslags.ToList();
RepeaterOpslag.DataBind();
List<ForslagOpslag> forslagopslag = db.ForslagOpslags.ToList();
foreach (ForslagOpslag item in forslagopslag)
{
var likesFjern = db.ForslagOpslagLikes.Where(a => a.fk_brugerid == Helper.ReturnBrugerId()).Count();
LabelBrugernavn.Text = item.brugere.fornavn + " " + item.brugere.efternavn;
LabelText.Text = item.text;
if (likesFjern >= 1)
{
LiteralLikesOpslag.Text = "<a href='fjernsynesgodtom.aspx?id=" + item.Id + "&brugerid=" + Helper.ReturnBrugerId() + "' class='btn btn-danger btn-xs'>Fjern synes godt om</a>";
}
else if (item.brugere.Id != Helper.ReturnBrugerId())
{
LiteralLikesOpslag.Text = "<a href='SynesGodtOm.aspx?id=" + item.Id + "' class='btn btn-success btn-xs'>Like opslag - " + item.ForslagOpslagLikes.Count() + " synes godt om</a>";
}
else
{
LiteralLikesOpslag.Text = "<p class='label label-lg label-success'>" + item.ForslagOpslagLikes.Count() + " synes godt om</p>";
}
if ((item.fk_brugerid == Helper.ReturnBrugerId() || Helper.BrugerRank(Helper.ReturnBrugerId()) == 1))
{
LiteralDelete.Text = "<a href='slet.aspx?id=" + item.Id + "' class='btn btn-danger btn-xs'>Slet</a>";
}
}

how Prevent Twice Page_Load Running - Page.IsPostBack Is always false

in a strange situation my page_Load Runs twice and all of my codes are in page_Load.
i can not use Page.IsPostBac because in both of Page_Loads, it is false.
but what is strange situation ?
i have a page for download files in my project,
when you click on one of download links (i used anchors, so IsPostBack is false) page_Load runs and in page load i check DownloadPath Querystring.
if DownloadPath not be null i jump to a Handler.ashx by passing that DownloadPath for showing Download Window To My Users.
during this process i have some logs in my database and because of that twice running they will be duplicate.
but when twice running accours ?
when you try to download a link by internet download manager, page_Load runs twice!
how can i prevent second runing of page_Load or is there a way for recognize it?
EDIT :
my page_Load :
namespace NiceFileExplorer.en
{
public partial class Download : System.Web.UI.Page
{
public string Folders = "";
public string Files = "";
protected void Page_Load(object sender, EventArgs e)
{
Statistics_body_inside.DataBind();
if (Request.QueryString["Path"] != null)
{
if (Request.QueryString["Path"] == "..")
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDoThatAnyMore", "YouCanNotDoThatAnyMore();", true);
}
else
{
MainCodes();
}
}
else
{
MainCodes();
}
}
private void MainCodes()
{
if (Request.QueryString["DownloadPath"] != null)
{
string DownloadPath = Request.QueryString["DownloadPath"].ToString();
string FilePath = "C:" + DownloadPath.Replace(#"/", #"\\");
if (Session["User_ID"] != null)
{
string FileName = Request.QueryString["FileName"].ToString();
string FileSize = Request.QueryString["FileSize"].ToString();
string FileCreationDate = Request.QueryString["FileCreationDate"].ToString();
int Downloaded_Count_4Today = DataLayer.Download.Count_By_UserID_Today(int.Parse(HttpContext.Current.Session["User_ID"].ToString()), DateTime.Now);
if (Downloaded_Count_4Today <= 10)
{
DataSet dsDownload = DataLayer.Download.Size_By_UserID_Today(int.Parse(HttpContext.Current.Session["User_ID"].ToString()), DateTime.Now);
if (dsDownload.Tables["Download"].Rows.Count > 0)
{
DataRow drDownload = dsDownload.Tables["Download"].Rows[0];
int SumOfFileSize4Today = int.Parse(drDownload["FileSizSum"].ToString());
if (SumOfFileSize4Today + int.Parse(FileSize) <= 1073741824)//1 GB = 1024*1024*1024 bytes = 1073741824 bytes
//if (SumOfFileSize4Today + int.Parse(FileSize) <= 100000)
{
//DataLayer.Download.InsertRow(
// int.Parse(Session["User_ID"].ToString()),
// DateTime.Now,
// FilePath.Replace(#"\\", #"\"),
// FileName,
// FileSize,
// DateTime.Parse(FileCreationDate)
// );
Response.Redirect("~/HandlerForMyFE.ashx?Downloadpath=" + HttpUtility.UrlEncode(DownloadPath));
}
else
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDownloadAnyMore_SizeOverload", "YouCanNotDownloadAnyMore_SizeOverload();", true);
}
}
else
{
if (int.Parse(FileSize) <= 1073741824)
//if (int.Parse(FileSize) <= 100000)
{
//DataLayer.Download.InsertRow(
// int.Parse(Session["User_ID"].ToString()),
// DateTime.Now,
// FilePath.Replace(#"\\", #"\"),
// FileName,
// FileSize,
// DateTime.Parse(FileCreationDate)
// );
Response.Redirect("~/HandlerForMyFE.ashx?Downloadpath=" + HttpUtility.UrlEncode(DownloadPath));
}
else
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDownloadAnyMore_SizeOverload", "YouCanNotDownloadAnyMore_SizeOverload();", true);
}
}
}
else
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "YouCanNotDownloadAnyMore_CountOverload", "YouCanNotDownloadAnyMore_CountOverload();", true);
}
}
else
{
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "plzLoginFirst_ForDownload", "plzLoginFirst_ForDownload();", true);
}
}
DirectoryInfo dir;
string lastpath = "";
try
{
lastpath = Request["path"].ToString();
}
catch { }
lblTitleInHeader.Text = "Files";
lblTitleInHeader.Text += lastpath;
//set back
string[] splited = lblTitleInHeader.Text.Split('/');
lblTitleInHeader.Text = "";
ArrayList arName = new ArrayList();
for (int i = 0; i < splited.Length; i++)
{
if (splited[i] != "")
{
arName.Add(splited[i]);
}
}
for (int i = 0; i < arName.Count - 1; i++)
{
if (i != arName.Count - 1)
{
lblTitleInHeader.Text += "<a href='Download.aspx?path=%2f";//%2f = /
for (int j = 1; j < i + 1; j++)
{
lblTitleInHeader.Text += HttpUtility.UrlEncode(arName[j].ToString() + "/");
}
lblTitleInHeader.Text += "'>" + arName[i] + "</a>" + " " + "<img class='icoSubFolder' src='../Images/Download/icoSubFolder.png' />";
}
}
lblTitleInHeader.Text += arName[arName.Count - 1].ToString();
lblTitleInHeader.Text = lblTitleInHeader.Text.Replace("/'>", "'>");
if (lastpath != "")
{
//dir = new DirectoryInfo(Server.MapPath("~/Files/" + lastpath));
dir = new DirectoryInfo(#"C:\\Files\\" + lastpath.Replace(#"/", #"\\"));
}
else
{
//dir = new DirectoryInfo(Server.MapPath("~/Files/"));
dir = new DirectoryInfo(#"C:\\Files\\");
}
int count4Folders = 0;
foreach (DirectoryInfo d in dir.GetDirectories())
{
count4Folders++;
DirectoryInfo dirSub = new DirectoryInfo(d.FullName);
int iDir = 0;
int iFile = 0;
foreach (DirectoryInfo subd in dirSub.GetDirectories())
{
iDir++;
}
foreach (FileInfo f in dirSub.GetFiles("*.*"))
{
iFile++;
}
Folders += "<div class='divFoldersBody_Row'>";
Folders += "<div class='divFoldersBody_Left'>";
Folders += " ";
Folders += "</div>";
Folders += "<div class='divFoldersBody_Name'>";
Folders += "<span class='imgFolderContainer'><img class='imgFolder' src='../Images/Download/folder.png' /></span>";
Folders += "<span class='FolderName'><a class='FolderLink' href='Download.aspx?path=" + HttpUtility.UrlEncode(lastpath + "/" + d.Name) + "'>";
Folders += d.Name;
Folders += "</a></span>";
Folders += "</div>";
Folders += "<div class='divFoldersBody_Count'>";
Folders += iDir.ToString() + " Folders & " + iFile.ToString() + " Files";
Folders += "</div>";
Folders += "<div class='divFoldersBody_Right'>";
Folders += " ";
Folders += "</div>";
Folders += "</div>";
}
if (count4Folders == 0)
{
divFoldersHeader.Style.Add("display", "none");
}
int count4Files = 0;
foreach (FileInfo f in dir.GetFiles("*.*"))
{
count4Files++;
Files += "<div class='divFilesBody_Row'>";
Files += "<div class='divFilesBody_Left'>";
Files += " ";
Files += "</div>";
Files += "<div class='divFilesBody_Name'>";
char[] Extension_ChAr = f.Extension.ToCharArray();
string Extension_str = string.Empty;
int lenghth = Extension_ChAr.Length;
for (int i = 1; i < Extension_ChAr.Length; i++)
{
Extension_str += Extension_ChAr[i];
}
if (Extension_str.ToLower() == "rar" || Extension_str.ToLower() == "zip" || Extension_str.ToLower() == "zipx" || Extension_str.ToLower() == "7z" || Extension_str.ToLower() == "cat")
{
Files += "<span class='imgFileContainer'><img class='imgFile-rar' src='../Images/Download/file-rar.png' /></span>";
}
else if (Extension_str.ToLower() == "txt" || Extension_str.ToLower() == "doc" || Extension_str.ToLower() == "docx")
{
Files += "<span class='imgFileContainer'><img class='imgFile-txt' src='../Images/Download/file-txt.png' /></span>";
}
else if (Extension_str.ToLower() == "pdf")
{
Files += "<span class='imgFileContainer'><img class='imgFile-pdf' src='../Images/Download/file-pdf.png' /></span>";
}
else if (Extension_str.ToLower() == "jpg" || (Extension_str.ToLower() == "png") || (Extension_str.ToLower() == "gif") || (Extension_str.ToLower() == "bmp") || (Extension_str.ToLower() == "psd"))
{
Files += "<span class='imgFileContainer'><img class='imgFile-image' src='../Images/Download/file-image.png' /></span>";
}
else if (Extension_str.ToLower() == "exe")
{
Files += "<span class='imgFileContainer'><img class='imgFile-exe' src='../Images/Download/file-exe.png' /></span>";
}
else
{
Files += "<span class='imgFileContainer'><img class='imgFile-unknown' src='../Images/Download/file-unknown.png' /></span>";
}
Files += "<span title='" + f.Name + "' class='FileName'>";
Files += f.Name;
Files += "</span>";
Files += "</div>";
Files += "<div class='divFilesBody_FileType'>";
Files += "<span style='color:red;'>" + Extension_str.ToUpper() + "</span>" + " File";
//Files += Path.GetExtension(f.Name) + " File";
Files += "</div>";
Files += "<div class='divFilesBody_FileSize'>";
Files += ConvertBytes.ToFileSize(long.Parse(f.Length.ToString()));
Files += "</div>";
Files += "<div class='divFilesBody_FileCreationDate'>";
Files += f.CreationTime;
Files += "</div>";
Files += "<div class='divFilesBody_FileDownload'>";
string Downloadpath = "/Files" + lastpath + "/" + f.Name;
string EncodedDownloadpath = HttpUtility.UrlEncode(Downloadpath);
Files += "<a class='FileLink' href='Download.aspx?path=" + HttpUtility.UrlEncode(lastpath) + "&Downloadpath=" + EncodedDownloadpath + "&FileName=" + HttpUtility.UrlEncode(f.Name) + "&FileSize=" + HttpUtility.UrlEncode(f.Length.ToString()) + "&FileCreationDate=" + HttpUtility.UrlEncode(f.CreationTime.ToString()) + "'>";
Files += "<img class='imgDownload' src='../Images/Download/Download.png' />";
Files += "</a>";
Files += "</div>";
Files += "<div class='divFilesBody_Right'>";
Files += " ";
Files += "</div>";
Files += "</div>";
}
if (count4Files == 0)
{
divFilesHeader.Style.Add("display", "none");
}
if ((count4Folders == 0) && (count4Files == 0))
{
divFoldersHeader.Style.Add("display", "block");
divFilesHeader.Style.Add("display", "block");
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "hash", "location.hash = '#BreadCrumbInDownload';", true);
}
....
my aspx :
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<link href="css/Download.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$('#Download-body *').css({ 'zIndex': 2 });
$('#Download-body').css({ 'overflow': 'hidden', 'position': 'relative' });
var containerWidth = $('#Download-body').innerWidth();
var containerHeight = $('#Download-body').innerHeight();
var bgimgurl = $('#Download-body').css('backgroundImage').replace(/url\(|\)|"|'/g, "");
var img = $('<img src="' + bgimgurl + '" width="' + containerWidth + 'px"' + ' height="' + containerHeight + 'px" />').css({ 'position': 'absolute', 'left': 0, 'top': 0, 'zIndex': 1 });
$('#Download-body').css({ 'background': 'transparent' }).append(img);
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div id="Download">
<div id="Download-header">
<div id="DownloadTitle">
Download
</div>
<asp:Image ID="imgDownload_header_left" runat="server" ImageUrl="~/Images/Download-header-left.png" />
<asp:Image ID="imgDownload_header_right" runat="server" ImageUrl="~/Images/Download-header-right.png" />
</div>
<div id="Download-body">
<div id="Download-body-inside">
<div id="Statistics">
<div id="Statistics-header">
<div id="StatisticsTitle">
Statistics
</div>
<asp:Image ID="imgStatistics_header_left" runat="server" ImageUrl="~/Images/Statistics-header-left.png" />
<asp:Image ID="imgStatistics_header_right" runat="server" ImageUrl="~/Images/Statistics-header-right.png" />
</div>
<div id="Statistics-body">
<div runat="server" id="Statistics_body_inside">
<asp:Label ID="lblDownload_Count_By_UserID_Title" runat="server" Text="Ur Download Count :"
ToolTip="Your Download Count From The Begining Of Registration UpTo Now" CssClass="lblTitleInStatistics"></asp:Label>
<asp:Label ID="lblDownload_Count_By_UserID" runat="server" Text="<%# Download_Count_By_UserID() %>"
CssClass="lblCountInStatistics"></asp:Label>
<br />
<asp:Label ID="lblDownload_Count_By_UserID_Today_Title" runat="server" Text="Ur Download Count-Today :"
ToolTip="Your Download Count-Today" CssClass="lblTitleInStatistics"></asp:Label>
<asp:Label ID="lblDownload_Count_By_UserID_Today" runat="server" Text="<%# Download_Count_By_UserID_Today() %>"
CssClass="lblCountInStatistics"></asp:Label>
<br />
<asp:Label ID="lblDownload_Size_By_UserID_Title" runat="server" Text="Ur Download Size :"
ToolTip="Your Download Size From The Begining Of Registration UpTo Now" CssClass="lblTitleInStatistics"></asp:Label>
<asp:Label ID="lblDownload_Size_By_UserID" runat="server" Text="<%# Download_Size_By_UserID() %>"
CssClass="lblCountInStatistics"></asp:Label>
<br />
<asp:Label ID="lblDownload_Size_By_UserID_Today_Title" runat="server" Text="Ur Download Size-Today :"
ToolTip="Your Download Size-Today" CssClass="lblTitleInStatistics"></asp:Label>
<asp:Label ID="lblDownload_Size_By_UserID_Today" runat="server" Text="<%# Download_Size_By_UserID_Today() %>"
CssClass="lblCountInStatistics"></asp:Label>
<br />
<asp:Label ID="lblDownload_Size_By_UserID_Today_Remain_Title" runat="server" Text="Ur Remain Download Size-Today :"
ToolTip="Your Remain Download Size-Today" CssClass="lblTitleInStatistics"></asp:Label>
<asp:Label ID="lblDownload_Size_By_UserID_Today_Remain" runat="server" Text="<%# Download_Size_By_UserID_Today_Remain() %>"
CssClass="lblCountInStatistics"></asp:Label>
</div>
</div>
</div>
<div id="MainDivInDownload">
<div id="BreadCrumbInDownload">
<div id="imgicoHomeContainer">
<asp:Image ID="imgicoHome" runat="server" ImageUrl="~/Images/Download/icoHome.png" />
</div>
<div id="lblTitleInHeaderContainer">
<asp:Label ID="lblTitleInHeader" runat="server" Text=""></asp:Label>
</div>
<div style="clear: both;">
</div>
</div>
<div runat="server" id="divFolders">
<div runat="server" id="divFoldersHeader">
<div id="divFoldersHeader_Left">
<asp:Image ID="divFoldersHeader_imgLeft" runat="server" ImageUrl="~/Images/Download/divsHeader_Left.png" />
</div>
<div id="divFoldersHeader_Name">
Folders In This Folder
</div>
<div id="divFoldersHeader_Count">
Total Files In This Folder
</div>
<div id="divFoldersHeader_Right">
<asp:Image ID="divFoldersHeader_imgRight" runat="server" ImageUrl="~/Images/Download/divsHeader_Right.png" />
</div>
</div>
<div id="divFoldersBody">
<%-- <div class="divFoldersBody_Row">
<div class="divFoldersBody_Left">
</div>
<div class="divFoldersBody_Name">
<span class="imgFolderContainer">
<asp:Image CssClass="imgFolder" runat="server" ImageUrl="~/Images/Download/folder.png" />
</span><span class="FolderName"><a class="FolderLink" href="#">Folders In This Folder</a></span>
</div>
<div class="divFoldersBody_Count">
Total Files In This Folder
</div>
<div class="divFoldersBody_Right">
</div>
</div>--%>
<%= Folders %>
</div>
</div>
<div runat="server" id="divFiles">
<div runat="server" id="divFilesHeader">
<div id="divFilesHeader_Left">
<asp:Image ID="divFilesHeader_imgLeft" runat="server" ImageUrl="~/Images/Download/divsHeader_Left.png" />
</div>
<div id="divFilesHeader_Name">
Files In This Folder
</div>
<div id="divFilesHeader_FileType">
File Type
</div>
<div id="divFilesHeader_FileSize">
File Size
</div>
<div id="divFilesHeader_FileCreationDate">
File Creation Date
</div>
<div id="divFilesHeader_FileDownload">
</div>
<div id="divFilesHeader_Right">
<asp:Image ID="divFilesHeader_imgRight" runat="server" ImageUrl="~/Images/Download/divsHeader_Right.png" />
</div>
</div>
<div id="divFilesBody">
<%-- <div class="divFilesBody_Row">
<div class="divFilesBody_Left">
</div>
<div class="divFilesBody_Name">
<span class="imgFileContainer">
<asp:Image runat="server" ImageUrl="~/Images/Download/file.png" CssClass="imgFile" />
</span><span class="FileName">Files In This Folder</span>
</div>
<div class="divFilesBody_FileType">
File Type
</div>
<div class="divFilesBody_FileSize">
File Size
</div>
<div class="divFilesBody_FileCreationDate">
File Creation Date
</div>
<div class="divFilesBody_FileDownload">
<a class="FileLink" href="#">
<asp:Image CssClass="imgDownload" runat="server" ImageUrl="~/Images/Download.png" />
</a>
</div>
<div class="divFilesBody_Right">
</div>
</div>--%>
<%= Files %>
</div>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
thanks in advance
Please look at the html as it is rendered on the page:
Every time it's present
<img src=""/>
double postback can happen, for some browser...
If this is the trouble, you can resolve it setting a default, blank, image for every button
<asp:ImageButton ImageUrl="~/Images/blank.gif"...

Categories