Why input file is caching the old uploaded images? - c#

I have bootstrap modal popup that pops up to enable user to select images to upload, So when the user chooses images I have javascript function that add new <div> containing the filename, then the user click save to save the images on the database, every thing is working except the input file is caching the old images and uploading them again with the newly selected images.
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="functionalUpdatePanel">
<ContentTemplate>
<button title="إضافة مرفق" data-toggle="modal" class="uploadAttach" data-target="#myModal" ></button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-
labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
hidden="true"> </button>
<h4 class="modal-title" id="myModalLabel">إضافة مرفق</h4>
</div>
<div class="modal-body">
<asp:Label ID="lblMessage" runat="server" ForeColor="Green" />
<h5 style="margin-right:45%;font-weight:bold;font-
size:1.2em">اختر المرفق</h5>
<div class="uploadBtnDiv">
<input
style="cursor:pointer;opacity:0;width:100%;height:100%"
title="اختيار مرفق" type="file" id="myFile" name="myFile"
multiple="multiple" />
</div>
<br />
<br />
</div>
<div class="modal-footer">
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button style="width:100%
!important;" Text="حفظ" title="إرسال المرفق" CssClass="btn
btn-success" runat="server" ID="btnUpload"
OnClick="btnUploadClick" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger
ControlID="btnUpload" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</div>
</div>
</ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
and here is my java script function
$(document).on('change', '#myFile:visible', function() {
var files = $(this)[0].files;
var newLine;
for (var i = 0; i < files.length; i++) {
newLine = "<div class='attach-line'>" +
"<div class='attach-name'>" +
files[i].name.slice(0,25)+'...' +
"<i class='icon-trash remove attach-delete'></i>" +
"</div>" +
"<br/>"+
"</div>";
$("#myModal .modal-body").append(newLine);
// Clone the file selector, assign the name, hide and append it
$(this).clone().hide().attr('name', 'myFile[]').insertAfter($(this));
}
$(".remove").click(function(){
$(this).parent(".attach-name").remove();
});
});
and bellow is the code behind
protected void btnUploadClick(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("AppId", typeof(int));
dt.Columns.Add("Bytes", typeof(byte[]));
dt.Columns.Add("ImgNames", typeof(string));
dt.Columns.Add("ImgType", typeof(string));
dt.Columns.Add("DedicatedMemberId", typeof(int));
for (int i = 0; i < Request.Files.Count; i++)
{
if (Request.Files[i] != null && Request.Files[i].ContentLength > 0)
{
string fType = Request.Files[i].ContentType.Split('/')[1];
string fName = Path.GetFileName(Request.Files[i].FileName);
byte[] bytes = new BinaryReader(Request.Files[i].InputStream).ReadBytes(Request.Files[i].ContentLength);
dt.Rows.Add(Convert.ToInt32(hfAppId.Value), bytes, fName,
fType, Convert.ToInt32(ViewState["memberId"]));
}
}
string outputStr = AppsOperations.UpdateAttach("إرفاق صورة جديدة", "الطلبات ", dt, User.Identity.Name);
if (outputStr == "s")
{
string redirectStr = "AuditApp.aspx?seq=" + hfAttSeq.Value + "&&AppType=" + hfAppType.Value + "&&id=" + hfAppId.Value;
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('تم تحميل المرفق بنجاح');window.location='" + redirectStr + "';", true);
}
else if (outputStr == "f")
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + "تعذر تحميل المرفق" + "')", true);
}
}

i am able to find the answer, actually i use the same code in another page to cache images for the use so i removed this the bellow line from java script function
$(this).clone().hide().attr('name', 'myFile[]').insertAfter($(this));

Related

Upoladed File Is Corrupt After Upload

I have a problem with my webapplication. I have made an upload-function for uploading documents. one For Answer Paper And Another Is Question Paper. I have No problem In Question Papeer Its Works Fine But When After Upload Answer Paper is Corrupt..
Any Idia
<div >
<label class="control-label" for="fileInput">Attached Question File </label>
<div class="controls">
<asp:FileUpload ID="fuQFile" runat="server" onChange="chngFUvalue(this)" CssClass="input-file uniform_on" />
<asp:Label ID="lblQVfile" runat="server" Text=""></asp:Label></div>
</div>
<div class="control-group">
<label class="control-label" for="fileInput">Attached Answer File </label>
<div class="controls">
<asp:FileUpload ID="fuAFile" runat="server" onChange="chngFUvalue(this)" CssClass="input-file uniform_on" />
<asp:Label ID="lblAVfile" runat="server" Text=""></asp:Label></div>
</div>
///For Question Pappr(Works Fine)////
string VQFile = "", VQFilePath = "";
if (fuQFile.HasFile)
{
VQFile = fuQFile.FileName.ToString();
VQFilePath = "1upload/files/Question/" + VQFile;
fuQFile.SaveAs(Server.MapPath("~/1upload/files/Question/") + VQFile);
}
else
{
VQFilePath = lblQVfile.Text;
}
// For Answer Paper(Facing Problem With That Part)////File Is Corrupt After Upload//////
if (fuAFile.HasFile)
{
VAFile = rndnom + "-" + fuAFile.FileName.ToString();
VAFilePath = "1upload/files/Answer/" + VAFile;
fuQFile.SaveAs(Server.MapPath("~/1upload/files/Answer/") + VAFile);
}
else
{
VAFilePath = lblAVfile.Text;
}
Your are calling fuQFile.SaveAs when saving the answer file, rather than fuAFile.SaveAs.

asp:button onclick doesn't fire and page only refreshes

Here's my aspx code for my button:
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
And here's the function for the onclick event in a codebehind file:
public void Button1_Click(object sender, EventArgs e)
{
lblOutput.Text = txtFirstName.Text;
}
Alternatively, I've also used this in the onclick function, to see if the problem was the problem was the script in the function and not the button itself:
public void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("http://www.google.com");
}
Unfortunately this didn't work either. So the problem is probably something going wrong when the button is clicked, right?
The code behind is properly linked, because other functions in the page_load are working fine.
All that happens when my button is clicked is the page refreshes. To be honest I'm not sure if I could call it a refresh, the values in the from are still there, the page just jumps back to the top and nothing else happens.
I've also tried creating a second button, with a slightly different ID and onclick name, but the page still acts the same. I'm at a complete loss here. I haven't found anything on google that helps.
EDIT: Here's the full asp file. We're using ektron as a CMS so there's some weird code for that as well. And before anybody asks, yes it's in a form tag.
<%# Page Language="C#" MasterPageFile="~/InteriorPage.master" AutoEventWireup="true" CodeFile="urmintakeform.cs" Inherits="urmintakeform" Debug="true" %>
<%# Register Assembly="Ektron.Cms.Controls" Namespace="Ektron.Cms.Controls" TagPrefix="CMS" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<asp:Literal ID="Literal1" runat="server" />
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="PageBody" Runat="Server">
<div id="two-column-pagenav" class="section-divider-small">
<div class="column-one"><h2>University Relations and Marketing</h2></div>
<div class="column-two">
<p class="breadcrumb">
<CMS:FolderBreadcrumb ID="FolderBreadcrumb1" runat="server" DynamicParameter="id" SuppressWrapperTags="true" SuppressAddEdit="true" />
</p>
</div>
</div>
<div>
<img alt="URM Banner" src="/images/department_banners/urm-banner.jpg" />
<asp:Literal ID="litDeptImage" runat="server" />
</div>
<div id="" class="container section-divider-small">
<div class="column-one">
<div class="nav-aside widget">
<div class="opener-block">
<span>Menu</span>
<span class="title">University Relations and Marketing</span>
</div>
<div class="nav-page-box nav-slide">
<!--Replace this code with the Ektron Flex Menu Control-->
<CMS:FlexMenu ID="FlexMenu1" runat="server" SuppressAddEdit="true" DefaultMenuID="15032386736" DisplayXslt="xml/departments.xsl" SuppressWrapperTags="true" CacheInterval="0" AllowClose="true" EnableSmartOpen="True" AutoCollapseBranches="True" StartCollapsed="True" />
</div>
</div>
<div class="widget-holder">
<div class="dept-contact-box widget">
<h4>How to Reach Us</h4>
<p><span style="font-weight: bold">University Relations and Marketing</span><br />
xxxx<br />
xxxx<br />
xxxxx<br />
xxxx<a href="tel:xxxxxxxxxxxxxxxxxxxxxxx</a><br />
Email: xxxxxxxxxxxxxxxxxxx<br />
</p>
<div class="dept-social-media">
<a title="Twitter" href="xxxxxxxxxxxxxxx" target="_blank">
<img src="/images/socmed_icons/twitter-32x432.png" alt="Twitter" title="Twitter" />
</a>
</div>
</div>
</div>
</div>
<div id="body-content" class="column-two">
<div class="content-body">
<div id="ctl00_PageBody_ContentBlock1" class="content-container">
<div class="content-holder">
<asp:Literal ID="litInPageTopNav" runat="server" />
<asp:Literal ID="ltrContent" runat="server" />
<CMS:FormBlock ID="FormBlock1" runat="server" DynamicParameter="ekfrm" />
</div>
</div>
<div class="intake">
<h2>Tell us about yourself</h2>
<div class="userinfo">
<label id="firstname" runat="server" text="First Name:" >First Name:</label>
<asp:TextBox ID="txtFirstName" runat="server" MaxLength="50" placeholder="First Name"></asp:TextBox><p></p>
<label id="lblLastName" runat="server" text="">Last Name:</label>
<asp:TextBox ID="txtLastName" runat="server" MaxLength="50" placeholder="Last Name"></asp:TextBox><p></p>
<label id="lblDepartment" runat="server" text="">Department:</label>
<asp:TextBox ID="txtDepartment" runat="server" MaxLength="50" placeholder="Department"></asp:TextBox><p></p>
</div>
<!-- Phone and Email --------->
<div class="job">
<label id="lblPhone" runat="server" text="">Phone:</label>
<asp:TextBox ID="txtPhone" runat="server" MaxLength="50" placeholder="Phone"></asp:TextBox><p></p>
<label id="lblEmail" runat="server" text="Email">Email:</label>
<asp:TextBox ID="txtEmail" runat="server" MaxLength="50" placeholder="Email"></asp:TextBox><p></p>
</div>
<div style="clear:both;"></div>
<div class="help">
<h2>How can we help you?</h2>
<label id="lblCategory" runat="server" text="Help">Get Help With: </label>
<select name="areaselector" id="areaselector">
<option value="select">Select an Option</option>
<option value="design">Design</option>
<option value="imprinted">Imprinted</option>
<option value="photography">Photography</option>
<option value="social">Social Media</option>
<option value="written">Written Content</option>
</select>
<div id="design" class="areas" style="display:none" onchange="">
<asp:CheckBoxList ID="designASP" runat="server" OnSelectedIndexChanged="appendToSelectedList">
<asp:ListItem Value="brochures">Brochures</asp:ListItem>
<asp:ListItem Value="posters">Posters</asp:ListItem>
<asp:ListItem Value="postcards">Postcards</asp:ListItem>
<asp:ListItem Value="booklets">Booklets</asp:ListItem>
<asp:ListItem Value="advertisement">Advertisement Design</asp:ListItem>
<asp:ListItem Value="digitalMarketing">Digital Marketing Material</asp:ListItem>
<asp:ListItem Value="other">Other Promotional Material</asp:ListItem>
</asp:CheckBoxList>
</div>
<div id="imprinted" class="areas" style="display:none">
<asp:CheckBoxList ID="imprintedASP" runat="server" OnSelectedIndexChanged="appendToSelectedList">
<asp:ListItem Value="licensed vendors">Licensed Vendors</asp:ListItem>
<asp:ListItem Value="Imprinted product search/sample products">Imprinted product search/sample products</asp:ListItem>
<asp:ListItem Value="billboard leasing">Billboard Leasing</asp:ListItem>
<asp:ListItem Value="Imprinted product art/design">Imprinted product art/design</asp:ListItem>
<asp:ListItem Value="table covers">Table covers</asp:ListItem>
<asp:ListItem Value="retractable banners">Retractable banners</asp:ListItem>
<asp:ListItem Value="temporary signage">Temporary signage</asp:ListItem>
<asp:ListItem Value="tigerizing">"Tigerizing"</asp:ListItem>
</asp:CheckBoxList>
</div>
<div id="photography" class="areas" style="display:none">
<asp:CheckBoxList ID="photographyASP" runat="server" OnSelectedIndexChanged="appendToSelectedList">
<asp:ListItem Value="Official faculty and staff portraits">Official facutly and staff portraits</asp:ListItem>
<asp:ListItem Value="Groups and/or organizatoin portraits">Groups and/or organization Portraits</asp:ListItem>
<asp:ListItem Value="Organization Event photos">Organization Event photos</asp:ListItem>
<asp:ListItem Value="Student Event photos">Student Event photos</asp:ListItem>
<asp:ListItem Value="Departmental brochure and web photos">Departmental brochure and web photos</asp:ListItem>
<asp:ListItem Value="Sporting events">Sporting events</asp:ListItem>
<asp:ListItem Value="Guest speakers">Guest speakers</asp:ListItem>
<asp:ListItem Value="ID and/or nametags">ID and/or nametags</asp:ListItem>
<asp:ListItem Value="Visa\passports photographs">Visa\passports photographs</asp:ListItem>
<asp:ListItem Value="Scanning, retouching and custom printing">Scanning, retouching and custom printing</asp:ListItem>
<asp:ListItem Value="Archive/history FHSU image retrieval">Archive/history FHSU image retrieval</asp:ListItem>
</asp:CheckBoxList>
</div>
<div id="social" class="areas" style="display:none">
<asp:CheckBoxList ID="socialASP" runat="server" OnSelectedIndexChanged="appendToSelectedList">
<asp:ListItem Value="Training">Training</asp:ListItem>
<asp:ListItem Value="Event coverage">Event coverage</asp:ListItem>
<asp:ListItem Value="Marketing/promotion">Marketing/Promotion</asp:ListItem>
</asp:CheckBoxList>
</div>
<div id="written" class="areas" style="display:none">
<asp:CheckBoxList ID="writtenASP" runat="server" OnSelectedIndexChanged="appendToSelectedList">
<asp:ListItem Value="Print">Print</asp:ListItem>
<asp:ListItem Value="Web">Web</asp:ListItem>
</asp:CheckBoxList>
</div>
</div>
<div class="tellusmore">
<h2>Tell us more about your request</h2>
<asp:TextBox ID="tellUsMoreBox" TextMode="MultiLine" runat="server" Columns="50" Rows="6" />
</div>
<!--<asp:Button ID="btnSubmit" runat="server" Text="Submit Application" Enabled="true" CssClass="submit" onclick="btnSubmit_Click" />
<asp:Button ID="asdf" runat="server" Text="Submit Application" Enabled="true" CssClass="submit" OnClick="btnSubmit_Click" />-->
<asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" CausesValidation="false"/>
</div>
</div>
</div>
</div>
</asp:Content>
Here's the C# file:
protected void Page_Load(object sender, EventArgs e)
{
ContentBlock ContentBlock1 = new ContentBlock();
ContentBlock1.SuppressWrapperTags = true;
ContentBlock1.DefaultContentID = 64;
ContentBlock1.DynamicParameter = "id";
ContentBlock1.Page = this.Page;
ContentBlock1.Fill();
//this.ltrContent.Text = ContentBlock1.Text.Replace("width", "max-width");
string lsContent = ContentBlock1.Text.Replace("width:", "max-width:");
lsContent = lsContent.Replace("width=", "max-width=");
//this.ltrContent.Text = lsContent;
//this.ContentBlock1.Text = lsContent;
FolderBreadcrumb1.Text += " > " + new CultureInfo("en").TextInfo.ToTitleCase(Server.HtmlDecode(ContentBlock1.EkItem.Title)) + "";
// dynamically generate an image if it been added as a meta image selector
Ektron.Cms.CustomAttributeList ContentMetaData;
ContentMetaData = ContentBlock1.GetMetaData();
if (ContentMetaData.GetItemByName("department-image").Value.ToString().Length > 0)
{
string extension;
extension = Path.GetExtension(Convert.ToString(ContentMetaData.GetItemByName("department-image").Value));
string ext = extension.Substring(0, 4);
if (ext == ".swf")
{
//is flash
litDeptImage.Text = "<object id=\"myId\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\"730\" height=\"175\">";
litDeptImage.Text += " <param name=\"movie\" value=\"" + Convert.ToString(ContentMetaData.GetItemByName("department-image").Value) + "\" />";
litDeptImage.Text += " <!--[if !IE]>-->";
litDeptImage.Text += " <object type=\"application/x-shockwave-flash\" data=\"" + Convert.ToString(ContentMetaData.GetItemByName("department-image").Value) + "\" width=\"730\" height=\"175\">";
litDeptImage.Text += " <!--<![endif]-->";
litDeptImage.Text += " <div>";
litDeptImage.Text += " <p>You have javascript turned off or are not running the latest version of Adobe Flash Player. To best view this site, please <img src=\"http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif\" alt=\"Get Adobe Flash player\" /></p>";
litDeptImage.Text += " </div>";
litDeptImage.Text += " <!--[if !IE]>-->";
litDeptImage.Text += " </object>";
litDeptImage.Text += " <!--<![endif]-->";
this.litDeptImage.Text += "</object>";
}
else
{
//else image
litDeptImage.Text = "<img class=\"ImageInline\" src=\"" + Convert.ToString(ContentMetaData.GetItemByName("department-image").Value) + "\" alt=\" \" />";
}
}
//grab collection id from the folder id that the content block belongs to
Ektron.Cms.API.Content.Content apiContent = new Ektron.Cms.API.Content.Content();
Ektron.Cms.Content.EkContent ekContent = apiContent.EkContentRef;
Microsoft.VisualBasic.Collection colldat = ekContent.GetAllCollectionsInfo(ContentBlock1.EkItem.FolderId, "id");
string collid = null;
foreach (Microsoft.VisualBasic.Collection field in colldat)
{
collid = field[1].ToString(); // collection id
}
long collint = Convert.ToInt64(collid);
//create the collection object we'll be using to get department nav pages
Ektron.Cms.Controls.Collection coll = new Collection();
coll.DefaultCollectionID = collint;
// set the standard coll properties
coll.DisplayXslt = "xml/departments-nav.xsl";
// attatch it to our invisible literal and fill it
coll.Page = Page;
coll.Fill();
if (!String.IsNullOrEmpty(collid))
litInPageTopNav.Text = coll.Text;
//Use the meta data we grabbed earlier to display title, keywords and description
Literal1.Text = "<title>" + Convert.ToString(ContentMetaData.GetItemByName("Title").Value) + " - xxxxxx University</title>\n";
Literal1.Text += "<meta name=\"keywords\" content=\"" + Convert.ToString(ContentMetaData.GetItemByName("Keywords").Value) + "\">\n";
Literal1.Text += "<meta name=\"description\" content=\"" + Convert.ToString(ContentMetaData.GetItemByName("Description").Value) + "\">\n";
//lblOutput.Text = Output;
}
public void Button1_Click(object sender, EventArgs e)
{
lblOutput.Text = txtFirstName.Text;
}
EDIT 2: Here's the tag that's on the page when viewing the pages source at run-time, provided by I believe possibly the master file. As I said earlier we use ektron cms. Could the form tag be a problem?
<form method="post" action="/urm/intake/" id="aspnetForm" onsubmit="if('undefined' == typeof Ektron || !Ektron.FormBlock || !typeof Ektron.FormBlock.validate || Ektron.FormBlock.validate(this)){$ektron('input[type=submit]').attr('disabled','disable');return true;}else{return false;}">
Figured it out. The CMS was the one at fault. I was viewing the page online with the URL given by the Ektron CMS. changing the formblock
<CMS:FormBlock ID="FormBlock1" runat="server" DynamicParameter="ekfrm" />
to a content block fixed it. The form block in ektron CMS caused problems.

ModalPopUp as User Control ASP.NET C#

Im trying build a ModalPopUp as Control. Its have theses controls:
TextBox- placeholder for filter
Button - Search Button
Button - Cancel Button
GridView - To show results
Screen of Search
<ajax:toolkitscriptmanager id="searchPopUp" runat="server"></ajax:toolkitscriptmanager>
<asp:Panel
BackColor="White"
ID="searchPanel"
CssClass="modalPopup"
runat="server"
Style="display: table">
<div class="myContainer">
<uc1:ScreenSearch
runat="server"
ID="mySearch" />
<asp:Button ID="btnToHide" runat="server" Text="Tohide" Style="display: none" />
<asp:Button ID="btnToShow" runat="server" Text="ToShow" Style="display: none" />
</div>
</asp:Panel>
<ajax:ModalPopupExtender
ID="ModalPopUpSearch"
runat="server"
TargetControlID="btnToShow"
PopupControlID="searchPanel"
CancelControlID="btnToHide"
DropShadow="true"
BackgroundCssClass="modalBackground">
</ajax:ModalPopupExtender>
code behind of : uc1:ScreenSearch
protected void Page_Load(object sender, EventArgs e){...}
protected void fillGridView()
{
myDao dao = new myDao();
DataSet ds = new DataSet();
ds = dao.retornarPesquisa(txtFilter.Text); //return data source
DataTable dt = new DataTable();
gv.DataSource = ds;
gv.DataBind();
}
uc1:ScreenSearch is my control that contain a TextBox, Button(perform search calling the method: fillGridView()) and GridView.
When I try perform the search click Binding the GridView. What the best way to get results in this GridView of my User Control?
You haven't posted any of your code so it's hard to tell why it's not working.Below is a working example which displays a Bootstrap modal popup -> allows a user to search -> displays the results in a GridView inside the modal popup:
Code behind:
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
}
public partial class ModalPopupFromGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSearch_Click(object sender, EventArgs e)
{
//Use txtSearch.Text to lookup the data you want to bind to the GridView, mine is hardcoded for the sake of simplicity
var p1 = new Person { Name = "Name 1", Surname = "Surname 1" };
var p2 = new Person { Name = "Name 2", Surname = "Surname 2" };
GridView1.DataSource = new List<Person> { p1, p2 };
GridView1.DataBind();
ScriptManager.RegisterStartupScript(this, this.GetType(), "myModal", "showPopup();", true);
}
}
.ASPX:
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script type="text/javascript">
//It'svery important that showPopup() is outside of jQuery document load event
function showPopup() {
$('#myModal').modal('show');
}
$(function () {
$(".show").click(function () {
showPopup();
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
Show Popup
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Details</h4>
</div>
<div class="modal-body">
<asp:TextBox ID="txtSearch" runat="server">
</asp:TextBox><asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" />
<br /><br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Surname" HeaderText="Surname" />
<asp:TemplateField HeaderText="User Details">
<ItemTemplate>
<a class="details" href="#" data-name='<%# Eval("Name") %>' data-surname='<%# Eval("Surname") %>'>Details</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</form>
</body>
Output:
Check if the search buttons autopostback is set to true. Also you will get the event of search button click in gridview_itemchanged event as the search button is inside gridview control. Hope that will work

ASP.NET How to bind data in DropDownList outside GridView?

I am creating a web aplication to access data in a SQL Server 2008 database. I show the data in a Gridview and I can succesfully edit the rows (even with DropDownLists), but I want to implement the edit of those records with a modal dialog/popup using Bootstrap.
However, I can not get working these DropDownLists in this modal, because resides in a DIV outside the <asp:GridView> element. I can bind others text fields in the modal dialog, with this code (the modal dialog is fired with a command ) [code_behind]:
if (e.CommandName.Equals("editRecord"))
{
GridViewRow gvrow = GridView2.Rows[index];
txtRUT.Text = HttpUtility.HtmlDecode(gvrow.Cells[2].Text);//.ToString();
txtDIGITO.Text = HttpUtility.HtmlDecode(gvrow.Cells[3].Text);
txtCOD_FISA.Text = HttpUtility.HtmlDecode(gvrow.Cells[4].Text);
txtNOMBRE.Text = HttpUtility.HtmlDecode(gvrow.Cells[5].Text);
//ddlCARGO is the DropDownList
ddlCARGO.Text = HttpUtility.HtmlDecode(gvrow.Cells[6].Text);
lblResult.Visible = false;
//I know that the DropDownList ist outside the GridView, but i don't know how to access/bind data to it
DropDownList combo_cargo = GridView2.Rows[index].FindControl("ddlCARGO") as DropDownList;
if (combo_cargo != null)
{
combo_cargo.DataSource = DataAccess.GetAllCargos(); //in GridView default edit mode, this works OK
combo_cargo.DataTextField = "cargo";
combo_cargo.DataValueField = "idCARGO";
combo_cargo.DataBind();
}
combo_cargo.SelectedValue = Convert.ToString(HttpUtility.HtmlDecode(gvrow.Cells[6].Text));
}
The modal html code [.aspx]:
<!-- EDIT Modal Starts here -->
<div id="editModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close"
data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="editModalLabel">Editar Empleado</h3>
</div>
<asp:UpdatePanel ID="upEdit" runat="server">
<ContentTemplate>
<div class="modal-body">
<p> Nombre: <asp:TextBox ID="txtNOMBRE" runat="server" columns="40"></asp:TextBox> </p>
<p>RUT: <asp:TextBox ID="txtRUT" runat="server" columns="8"></asp:TextBox> -
<asp:TextBox ID="txtDIGITO" runat="server" columns="1"></asp:TextBox></p>
<p>Código Fisa: <asp:TextBox ID="txtCOD_FISA" runat="server" columns="7"></asp:TextBox></p>
<%--<p>Cargo: <asp:TextBox ID="txtCARGO" runat="server" columns="7"></asp:TextBox></p>--%>
<p>Cargo: <asp:DropDownList ID="ddlCARGO" runat="server"></asp:DropDownList></p>
<%-- <p>Estado: <asp:TemplateField HeaderText="ESTADO" SortExpression="idESTADO">
<EditItemTemplate>
<asp:DropDownList ID="ddlESTADO" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblESTADO" runat="server" Text='<%# Bind("ESTADO") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField> </p> --%>
</div>
<div class="modal-footer">
<asp:Label ID="lblResult" Visible="false" runat="server"></asp:Label>
<asp:Button ID="btnSave" runat="server" Text="Update" CssClass="btn btn-info" OnClick="btnSave_Click" />
<button class="btn btn-info" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView2" EventName="RowCommand" />
<asp:AsyncPostBackTrigger ControlID="btnSave" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</div>
<!-- Edit Modal Ends here -->
I can give you an idea.
Create a DIV/user control with those controls that you need to edit.
On ROW click - open the DIV in model (jq you can use) and then either pass the Row content to the Model.open Or pass some unique ID of that ROW and load again from DB the Row corresponding detail. And allow editing there and on Save over there - saving to DB with that unique ID preserved.
Let us know
Finally I have found the solution:
Modal html (.aspx):
<div class="form-group">
<asp:TextBox ID="txtCARGO" runat="server" CssClass="hiddencol"></asp:TextBox> <%--data value field (hidden with CSS)--%>
<label class="col-xs-3 control-label" for="editModalCargo">Cargo</label>
<div class="col-xs-3 input_medio">
<asp:DropDownList id="editModalCargo" runat="server" name="editModalCargo" class="form-control input-md"/> <%--data text field--%>
</div>
</div>
<div class="form-group hiddencol"> <%--field with row id (hidden with CSS)--%>
<asp:TextBox ID="txtID" runat="server" columns="2"></asp:TextBox>
</div>
I've put OnRowCommand="GridView2_RowCommand" on <asp:GridView> and created a <asp:ButtonField> with CommandName="editRecord"> to edit the row.
Code behind (.aspx.cs):
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName.Equals("editRecord"))
{
GridViewRow gvrow = GridView2.Rows[index];
txtID.Text = HttpUtility.HtmlDecode(gvrow.Cells[17].Text); //Pass value from Gridview's column to <asp:TextBox ID="txtID">
txtCARGO.Text = HttpUtility.HtmlDecode(gvrow.Cells[13].Text); //Pass value from Gridview's column to <asp:TextBox ID="txtCARGO">
lblResult.Visible = false;
BindEditCargo(txtCARGO.Text);
}
}
private void BindEditCargo(string cargoValue) //Populates <asp:DropDownList id="editModalCargo">
{
editModalCargo.DataSource = DataAccess.GetAllCargos();
editModalCargo.DataTextField = "cargo";
editModalCargo.DataValueField = "idCARGO";
// Bind the data to the control.
editModalCargo.DataBind();
// Set the default selected item, if desired.
editModalCargo.SelectedValue = cargoValue;
}
DataAccess.cs:
public static DataTable GetAllCargos()
{
DataTable dt = new DataTable();
string sql = #"SELECT * FROM CARGO";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BRconn"].ToString()))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
return dt;
}
To read the value from modal (to pass it to a Update query for example), you can use (in code behind):
protected void btnSave_Click(object sender, EventArgs e) // Handles Update Button Click Event
{
int idEMPLEADO = Convert.ToInt32(txtID.Text); //Read value from <asp:TextBox ID="txtID">
int idCARGO = Convert.ToInt32(editModalCargo.SelectedValue); //Read value from <asp:DropDownList id="editModalCargo">
DataAccess.UpdateEmpleado(idEMPLEADO, idCARGO); //Update Query
BindData(); //Refresh Gridview
}

Dynamic jQuery 'add a textbox' to an asp:Repeater using C#

I'm having problems with a chunk of code that's meant to add a textbox to a Repeater in ASP.
I have the following:
<asp:Repeater ID="uxRolesList" runat="server">
<ItemTemplate>
<div id="<%# GetRolesDivId() %>" class="div_row">
<asp:TextBox ID="uxTxtBoxRole" runat="server" rows="5" columns="100" Text='<%# DataBinder.Eval(Container.DataItem, "RequirementDescription") %>' TextMode="multiline" MaxLength="2000"></asp:TextBox>
<input type="button" style="vertical-align:top;" value="X" class="remove-roles-btn" />
<br /><br />
</div>
</ItemTemplate>
</asp:Repeater>
Which generates a load of textboxes that look like this in the html:
<td id="rolesColumn">
<div id="roles-0" class="div_row">
<textarea name="ctl00$mainContent$uxRolesList$ctl00$uxTxtBoxRole" rows="5" cols="100" id="ctl00_mainContent_uxRolesList_ctl00_uxTxtBoxRole">Cool Job1</textarea>
<input type="button" style="vertical-align:top;" value="X" class="remove-roles-btn" />
<br /><br />
</div>
</td>
I've also added the following button, that should add a textbox to this list when hit:
<asp:Button CssClass="btn" ID="uxAddRoleBtn" runat="server" Text="Add a new role requirement" />
Using the following jQuery code:
$("#ctl00_mainContent_uxAddRoleBtn").live("click", (function (e) {
var rolesCounter = $('#ctl00_mainContent_uxTxtBoxRolesCount').val();
if (rolesCounter < 10) {
var rolesCounterText = "0" + rolesCounter;
} else {
var rolesCounterText = rolesCounter;
}
$('#rolesColumn').append("<div id='roles-" + rolesCounter + "' class='div_row'><textarea name='ctl00$mainContent$uxRolesList$ctl" + rolesCounterText + "$uxTxtBoxRole' rows='5' cols='100' id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxTxtBoxRole' MaxLength='2000' ></textarea><input type='submit' name='ctl00$mainContent$uxRolesList$ctl" + rolesCounterText + "$uxRemoveRoleBtn' value='X' id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxRemoveRoleBtn' class='remove-roles-btn' style='vertical-align:top;' /><br /><span id='ctl00_mainContent_uxRolesList_ctl" + rolesCounterText + "_uxValTxtBoxRole' style='color:Red;visibility:hidden;'>Please complete this role requirement</span><br /><br /></div>");
e.preventDefault();
rolesCounter++;
$('#ctl00_mainContent_uxTxtBoxRolesCount').val(rolesCounter);
}));
So far so good. I hit the add button and the textbox appears, I type something in, everything's great. The html look something like this:
<div id="roles-0" class="div_row">
<textarea id="ctl00_mainContent_uxRolesList_ctl00_uxTxtBoxRole" cols="100" rows="5" name="ctl00$mainContent$uxRolesList$ctl00$uxTxtBoxRole">Cool Job1</textarea><input class="remove-roles-btn" type="button" value="X" style="vertical-align:top;"><br><br>
</div>
<div id="roles-1" class="div_row">
<textarea id="ctl00_mainContent_uxRolesList_ctl01_uxTxtBoxRole" maxlength="2000" cols="100" rows="5" name="ctl00$mainContent$uxRolesList$ctl01$uxTxtBoxRole">Test</textarea><input class="remove-roles-btn" type="submit" style="vertical-align:top;" value="X" name="ctl00$mainContent$uxRolesList$ctl01$uxRemoveRoleBtn"><br><br>
</div>
Then I hit submit and the new values do not come through.
In the C# side I'm trying to access the data using:
foreach (RepeaterItem item in dl.Items)
{
System.Web.UI.WebControls.TextBox rb = item.FindControl(control) as System.Web.UI.WebControls.TextBox;
if (rb.Text.Trim() != "")
{
PositionRequirement pr = new PositionRequirement();
pr.RequirementDescription = rb.Text;
pr.RequirementLevel = new PositionRequirementLevel(level, levelDescription);
pr.OrderNumber = i;
i++;
positionRequirements.Add(pr);
}
}
where dl = uxRolesList
control = uxTxtBoxRole
I'm at an utter loss as to why the new values are not coming through with the uxRolesList Repeater.
What am I doing wrong?
from what i know , the approach used is not going to show the items that are added within the Repeater Datasource, unless they exist before the page is being served to the user, so in the example, only the items that were bound to the repeater before leaving the server (if any) will show.
if you don't want to leave the page and make a trip to the server on every add click,of the top my head i would suggest that you would access them via the request Object using the name instead of the id ( Request[""] ) and keep the name of each textbox similar ("txtbox1","txtbox2")and append the count as you did in your Jquery code, then on the server when the page is submitted loop over the items using the counter that you have stored in uxTxtBoxRolesCount.

Categories

Resources