Let me explain my project first of all.
Its a form with some information that I add in to textboxs and a signature field.
When you click on the signature it redirects you to another page where you sign and then goes back to the form and puts the signature in an image.
Point is when I go to the signature page I put the Form information in to a cookie so I can put them back on when I return from the signature page.
The problem is when it gets to the other page the cookie gets messed up content wise. If I try to write some simple hebrew on the page there is no problem.
This is the code that saves the cookie.
protected void ReCapture(object sender, EventArgs e)
{
string s = "";
foreach (Control c in form1.Controls)
{
if (c.GetType() == typeof(TextBox))
{
s += ((TextBox)c).Text + ":" + ((TextBox)c).ID + ",";
}
if (c.GetType() == typeof(Image))
{
s += ((Image)c).ImageUrl + ":" + ((Image)c).ID + ",";
}
}
Response.Cookies.Remove("Controls");
HttpCookie hc = new HttpCookie("Controls",s.Remove(s.Length - 2));
hc.Expires.AddHours(2);
hc.Path = "/";
Response.Cookies.Add(hc);
Response.Redirect("SignaturePage.aspx?id=" + ((Control)sender).ID);
}
This is the signature page code(practically nothing)
protected void Save(object sender, EventArgs e)
{
Session["TheSignature"] = Request.Form["TheData"];
Response.Redirect("Test.aspx");
}
Why is this happening?
Related
So while fooling around with webforms, I tried to create a page that outputs a table from a sql server to a html table on Page_Load. I then tried to add a button to a column which would redirect to a page. The only problem is, when I press the button nothing happens at all... I've tried putting breakpoints at the onclick method but they are never reached.
num = ds.Tables[0].Rows.Count;
htmlTable.Append("<tr style='background-color:#bd0000; color: White;'><th>ID</th><th>Job #</th><th>Project</th><th>Completed By</th><th>Date Created</th><th></th></tr>");
if (!object.Equals(ds.Tables[0], null))
{
if (ds.Tables[0].Rows.Count > 0)
{
int MAX_VIEW = (ds.Tables[0].Rows.Count > 15) ? 15 : ds.Tables[0].Rows.Count;
for (int i = 0; i < MAX_VIEW; i++)
{
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Job_Number"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["Project_Name"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["CompletedBy"] + "</td>");
htmlTable.Append("<td>" + ds.Tables[0].Rows[i]["DateCreated"] + "</td>");
htmlTable.Append("<td width=\"10%\"><button class=\"astext\" name=\"Btn" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "\" id =\"" + ds.Tables[0].Rows[i]["CCPOF_ID"] + "\" OnClick =\"btnEdit_Click\" runat=\"server\" >Edit</button> | Details</td>");
htmlTable.Append("</tr>");
}
htmlTable.Append("</table>");
DBDataPlaceHolder.Controls.Add(new System.Web.UI.WebControls.Literal { Text = htmlTable.ToString() });
}
else
{
htmlTable.Append("<tr>");
htmlTable.Append("<td align='center' colspan='4'>There is no Record.</td>");
htmlTable.Append("</tr>");
}
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
String id = ((System.Web.UI.WebControls.Button)sender).ID;
Server.Transfer("CcpofDetails.aspx?ID=" + id);
}
}
When I inspect the button in the live form this is what I see
<button class="astext" name="Btn10" id="10" onclick="btnEdit_Click" runat="server">Edit</button>
Your way of generating dynamic controls seems very strange to me. It is not the way web-forms work.
To run an event on a control, it has to be loaded into servers memory first. But you are just filling some html text that is understandable only for the browser, not for asp.net engine.
take a look at this sample
To give you a better idea, create your buttons like this
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
AddControls();
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (ViewState["controsladded"] == null)
AddControls();
}
private void AddControls()
{
TextBox dynamictextbox = new TextBox();
dynamictextbox.Text = "(Enter some text)";
dynamictextbox.ID = "dynamictextbox";
Button dynamicbutton = new Button();
dynamicbutton.Click += new System.EventHandler(dynamicbutton_Click);
dynamicbutton.Text = "Dynamic Button";
Panel1.Controls.Add(dynamictextbox);
Panel1.Controls.Add(new LiteralControl("<BR>"));
Panel1.Controls.Add(new LiteralControl("<BR>"));
Panel1.Controls.Add(dynamicbutton);
ViewState["controlsadded"] = true;
}
private void dynamicbutton_Click(Object sender, System.EventArgs e)
{
TextBox tb = new TextBox();
tb = (TextBox) (Panel1.FindControl("dynamictextbox"));
Label1.Text = tb.Text;
}
I believe your problem comes from the fact that ASP.NET doesn't know you created a button. As far as it's concerned, all you did was pump out some text to the page.
As a result, when you post back to the server, it doesn't know it needs to do anything on the server side when you click.
Try creating it as an object (a System.Web.UI.WebControls.Button) and adding that to your page's Controls collection. Be aware that you'll have to do this both on the initial page build and on postback: if the control doesn't exist after postback, events that were hooked up to it don't fire.
Getting it to appear in the middle of your table may require you to do your HTML table creation in some other way, such as building a WebControls Table object and adding that to your Controls collection.
You are not adding corectl the button to the web form. Try this way:
Button btnEdit = New Button();
btn.Edit.Click += btnEdit_Click;
frmMain.Controls.Add(btnSave)
As shown in this question too.
I use this code to find CDE in the HTML. How can I find my request data in tag page with different ids, for example if page id is 1 my result is CDE and when page id is 2 my result is IJK, How can I set id-value in my search?
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.DocumentText = #"<html><head><title></title></head><body>"
+ "<page id=\"1\">"
+ #"ABCDEF</page>"
+ "<page id=\"2\">"
+ #"GHIJKLMN</page></body></html>";
webBrowser1.DocumentCompleted += HtmlEditorDocumentCompleted;
}
void HtmlEditorDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var document = (IHTMLDocument2)((WebBrowser)sender).Document.DomDocument;
if (document != null)
{
IHTMLBodyElement bodyElement = document.body as IHTMLBodyElement;
if (bodyElement != null)
{
IHTMLTxtRange trg = bodyElement.createTextRange();
if (trg != null)
{
trg.move("character", 2);
trg.moveEnd("character", 3);
trg.select();
trg.pasteHTML("<font color=#FF0000><strike>" + trg.text + "</strike></font>");
}
}
}
}
I have no idea, what do you need to do, you may have to rephrase the question...
But you might want to have a look at webBrowser1.Document.GetElementDyId() to get a specific element by "id"
Okay here I have some code from my project at the moment.
Basically the user goes onto the page and their current password is in the password textbox, and their avatar is selected in the droplist.
They can change their password by editing the text in the textbox and change their avatar by selecting a new one from the list. This is then written to the file where this information is kept. It writes to the file okay, but it writes what was initially in the textbox and droplist.
If i comment out these lines in the page load:
avatarDropList.SelectedValue = Session["avatar"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
It updates the file properly, but this is not what I want as I want the old password displayed there initially as well as the avatar to be selected in the dropbox.
Code below:
public partial class TuitterProfile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
avatarImage.ImageUrl = "~/images/avatars/" + Session["avatar"] + ".gif";
avatarDropList.SelectedValue = Session["avatar"].ToString();
userNameTextbox.Text = Session["user"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
}
protected void okButton_Click(object sender, ImageClickEventArgs e)
{
string username = Session["user"].ToString();
string password = Session["password"].ToString();
string newPassword = newPasswordTextbox.Text;
string newAvatar = avatarDropList.SelectedValue;
int allDataReference = -1;
//Each element in the array is a string(Username Password Avatar)
string[] allData = File.ReadAllLines(Server.MapPath("~") + "/App_Data/tuitterUsers.txt");
for (int i = 0; i < allData.Length; i++)
{
string[] user = allData[i].Split(' ');
if (user[0] == username && user[1] == password)
{
allDataReference = i;
}
}
if (allDataReference > -1)
{
Session["avatar"] = newAvatar;
Session["password"] = newPassword;
allData[allDataReference] = username + " " + newPassword + " " + newAvatar;
File.WriteAllLines(Server.MapPath("~") + "/App_Data/tuitterUsers3.txt", allData);
}
}
}
In the ASP.Net page event lifecycle, Page_Load is called on every request. What you are doing here is resetting the value of the TextBox every time the page loads, which will include the time that you press the button to save the profile.
All you need to do is check for the current request being a postback when you set your initial values:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
avatarImage.ImageUrl = "~/images/avatars/" + Session["avatar"] + ".gif";
avatarDropList.SelectedValue = Session["avatar"].ToString();
userNameTextbox.Text = Session["user"].ToString();
newPasswordTextbox.Text = Session["password"].ToString();
}
}
I have a bunch of different panels that are custom server controls, which inherits CompositeControl. The panels are rendered by using the CreateChildControls(). I have a page where I am displaying them based off of a users selection from a comboBox. When you change the selection it does a callback for a callback panel (DevExpress control), which is like an update panel. Based on the selection it adds the panel to the callback panel. But it seems that if you do this from a callback the server controls life cycle doesn't get started, so it never calls CreateChildControls() or OnPreRender(). Any ideas on how to make this work? EnsureChildControls() doesn't seem to helping.
Here is some example code of one of the panels
protected override void CreateChildControls()
{
base.CreateChildControls();
String strParentID = this.ClientInstanceName.Length > 0 ? this.ClientInstanceName : this.ClientID;
String strID = "";//Used as ID and ClientInstanceName.
String strKey = "";//Used in the ID and as the ControlInfo key.
if (!DesignMode)
{
//*******************************************************************
ASPxLabel lblUnit = new ASPxLabel();
lblUnit.Text = "Select Unit(s)";
callbackEdit.Controls.Add(lblUnit);
//*******************************************************************
strKey = "btnUnitSelector";
strID = strParentID + "_" + strKey;
btnUnitSelector = new ASPxButton()
{
ID = strID,
ClientInstanceName = strID,
CssFilePath = this.CssFilePath,
CssPostfix = this.CssPostfix,
SpriteCssFilePath = this.SpriteCssFilePath,
};
btnUnitSelector.Width = Unit.Pixel(180);
btnUnitSelector.AutoPostBack = false;
this.listControlInfo.Add(new ControlInfo(strKey, btnUnitSelector.ClientInstanceName, btnUnitSelector.ClientID));
callbackEdit.Controls.Add(btnUnitSelector);
//*******************************************************************
strKey = "unitPopup";
strID = strParentID + "_" + strKey;
unitPopup = new UnitPopup.UnitPopup();
unitPopup.ID = strID;
unitPopup.ClientInstanceName = strID;
unitPopup.btnOk_AutoPostBack = false;
unitPopup.ShowOnlyUnits = false;
unitPopup.DataSource = GlobalProperties.Company_UnitsAndAreas;
unitPopup.DataBind();
btnUnitSelector.ClientSideEvents.Click = "function (s, e) { " + unitPopup.ClientInstanceName + ".Show(); }";
unitPopup.ClientSideEvents.MemberSet = "function (s, e) { " + btnUnitSelector.ClientInstanceName + ".SetText(" + unitPopup.ClientInstanceName + ".selectedMemberName); }";
Controls.Add(unitPopup);
//*******************************************************************
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ClientScriptManager cs = this.Page.ClientScript;
//Register an embedded JavaScript file. The JavaScript file needs to have a build action of "Embedded Resource".
String resourceName = "QSR_ServerControls.Controls.DashboardControls.SalesChart.SalesChart.js";
cs.RegisterClientScriptResource(typeof(SalesChart), resourceName);
}
Here is some sample code of adding a panel
private void PopulatePanel(string panel)
{
tblDescCell.Controls.Add(new LiteralControl(GetPanels().Select("[PanelName] = '" + panel + "'")[0]["PanelDescription"].ToString()));
if (panel == "SalesChart")
tblTopLeftCell.Controls.Add(new SalesChart.SalesChart());
}
void callbackMain_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
PopulatePanel(e.Parameter);
}
During callback requests PreRender and Render methods are not executed (this is the main difference from PostBack request). But CreateChildControls should be executed. Please provide more information or code example.
I am using the jQuery AjaxForm plugin
to create an preview of an image I the user select to load to the server.
I use an Http Handler to create an temp image file that is used for the image preview.
In response to client side 'onchange' event of the FileUpload control the image preview is created successfully.
I have a button that sends the whole form (UploadImageToServerStep1.aspx) to the server. In the server side Click event of that button I try to transfer the control to another page (UploadImageToServerStep1.aspx2),the control gets to the other page code behind file(The control gets to that page Page_Load event) but the page is not displayed - instead the referring page is displayed(UploadImageToServerStep1.aspx)again (the control do not go the page load event of that page).
The JS code in UploadImageToServerStep1.aspx is :
< script type = "text/javascript" >
var preview = {
ImagePreview: function(imageId) {
var formId = '<%= Form.ClientID %>';
var fileUploadId = '<%= FileUpload1.UniqueID %>';
var action = $('#' + formId).attr('action');
var imageName = $("input[serverId = 'FileUpload1']").val();
$('#' + formId).attr('action', './HttpHandlers/ImagesHandler.ashx?action=imagePreview&f=' + fileUploadId + '&i=' + imageName);
$('#' + formId).ajaxForm(function() {
$('#' + imageId).attr('src', './HttpHandlers/ImagesHandler.ashx?action=imagePreview&f=' + fileUploadId + '&i=' + imageName);
$('#' + imageId).show();
$('#' + formId).attr('action', action);
});
$('#' + formId).submit();
}
}; < /script>/
In UploadImageToServerStep1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FileUpload1.Attributes.Add("onchange", "preview.ImagePreview('htmlImgPreview');");
FileUpload1.Attributes.Add("serverId", "FileUpload1");
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Response.Redirect("UploadImageToServerStep2.aspx");
//Server.Transfer("UploadImageToServerStep2.aspx");
}
}
In the HttpHandler :
case "imagePreview":
string f = context.Request.QueryString.Get("f");
string i = context.Request.QueryString.Get("i");
const string uploadImageTempPath = "~/Images/TempImages/";
if (!string.IsNullOrEmpty(context.Request.QueryString.Get("i")) && context.Request.Files[f] != null)
{
HttpPostedFile file = context.Request.Files[f];
SaveImage(context, file, uploadImageTempPath, i);
}
context.Response.ContentType = GetContentType(context.Session["fileName"].ToString());
if (context.Session["fileName"] == null || context.Request["i"] == null)
{
return;
}
byte[] byteArray1 =
System.IO.File.ReadAllBytes(
context.Request.MapPath(string.Format("{0}{1}", uploadImageTempPath, context.Session["fileName"])));
context.Response.BinaryWrite(byteArray1);
break;
}
Can someone please write what is the cause for that behavior and how can I solve this problem
Thanks
When trying to do a response.redirect in response to an ajax call, your browser is not going to behave in the same way it would with a regular synchronous request. You can however, take the response and do something with it on the JS side. I believe this will help you.
Returning redirect as response to XHR request