Accessing hidden-input values edited by JavaScript - c#

I have dynamically created hidden input controls in a C# code-behind file, and then populated their values with JavaScript. I now want to access these variables in C#.
Firebug shows that the values do change with JavaScript, but I'm getting the original values back in the code behind. Any insight would be much appreciated.
JavaScript:
function injectVariables(){
var hidden = document.getElementById("point1");
hidden.value = 55;
var hidden2 = document.getElementById("point2");
hidden2.value = 55;
var hidden3 = document.getElementById("point3");
hidden3.value = 55;
alert("values changed");
}
ASPX:
<asp:Button OnClick="Update_PlanRisks" OnClientClick="injectVariables()" Text="updatePlanRisks" runat="server" />
C#:
protected override void CreateChildControls()
{
base.CreateChildControls();
int planId = Convert.ToInt32(Request.QueryString.Get("plan"));
planRisks = wsAccess.GetPlanRiskByPlanId(planId);
foreach (PlanRisk pr in planRisks)
{
HtmlInputHidden hiddenField = new HtmlInputHidden();
hiddenField.ID= "point" + pr.Id;
hiddenField.Name = "point" + pr.Id;
hiddenField.Value = Convert.ToString(pr.Severity);
this.Controls.Add(hiddenField);
}
}
protected void Update_PlanRisks(object sender, EventArgs e)
{
foreach (PlanRisk pr in planRisks)
{
int planRiskId = pr.Id;
string planRiskName = "point" + pr.Id;
HtmlInputHidden hiddenControl = (HtmlInputHidden) FindControl(planRiskName);
string val = hiddenControl.Value;
}
}

This is one way to get the value from the request...
string point1 = Request.Form["point1"];

In CreateChildControls you are explicitly setting the value of the hidden field(s). CreateChildControls runs each time during the page lifecycle (potentially multiple times), when you click submit, the page posts back and runs through the entire lifecycle again - including CreateChildControls - before running the click handler Update_PlanRisks.
The simplest way to avoid this problem is to check if you are in PostBack before setting the value of your hidden fields:
if(!IsPostBack)
{
hiddenField.Value = Convert.ToString(pr.Severity);
}

Related

Saving Data to the Database from Dynamically created asp.net textboxes

First off, I've seen a ton of posts for this same question but what I don't understand is when somebody gives an answer about "recreating the controls to page init" or ... I have the code to dynamically CREATE the text boxes but I'm not sure what else I need to add. I don't completely understand the page life cycle of asp.net web apps. I've googled this and I dont know if I'm incompetent or if all of the answers given are for people with more understanding than me.
PLEASE provide an example of what you explain.
Basically The user enteres a # into the textbox for how many "favorite books" they want to save into the database, he/she clicks the generate button.
that # of rows will populate with two textboxes, one for title and one for author. Then I would have a button they click that would save the textbox values into the database.
I know it's a simple exercise but I'm new to asp.net and it's just an exercise I came up by myself that I'm trying to learn. I'm open to new design for this but the one thing I prefer not to do is create the textboxes statically. Thanks! <3
this is the asp.net code I have
<form id="form1" runat="server">
<div>
How many favorite books do you have ?
<asp:TextBox ID="TextBox1" runat="server" Width="50px"></asp:TextBox>
<br />
<asp:Button ID="btnBookQty" runat="server" Text="GenerateBooks" OnClick="btnBookQty_Click" />
<br />
<br />
<asp:Panel ID="pnlBooks" runat="server"></asp:Panel>
</div>
</form>
and my c# code is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class databasetest_panels_favBookWebsite : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnBookQty_Click(object sender, EventArgs e)
{
int count = Convert.ToInt32(TextBox1.Text);
for (int i = 1; i <= count; i++)
{
TextBox tb = new TextBox();
TextBox tb2 = new TextBox();
tb.Text = "Book " + i.ToString() + " Title";
tb2.Text = "Book " + i.ToString() + " Author";
tb.ID = "TextBoxTitle" + i.ToString();
tb2.ID = "TextBoxAuthor" + i.ToString();
pnlBooks.Controls.Add(tb);
pnlBooks.Controls.Add(tb2);
pnlBooks.Controls.Add(new LiteralControl("<br />"));
}
}
}
You don't really need to keep track of your programmatically or dynamically added controls. It's true that somehow someone has to keep track of them, but it's not you who should be doing so.
Understanding the Page Life-cycle in ASP.NET Web Forms is a must for any ASP.NET developer. Sooner or later you'll run into this sort of problems that would be greatly simplified if you really understood the underlying mechanics of the page.
Each time a request is made to the server, the whole page must be assembled from scratch. You can read (please do) on the web the many steps or stages that make up the Page Life-cycle for an ASP.NET page, but for you to have a rough idea on how this works:
When the request is made, the .aspx file is parsed and a memory source code created from it. This stage is known as the Instantiation stage, and the page's control hierarchy is created at this point.
After that, page goes through the Initialization phase, in which the page's Init event is fired. This is "the place" to add controls dynamically.
LoadViewState phase comes next. At this point, the information of the controls that are part of the page's control hierarchy get their "state" updated to make them return to the state they were before the postback. (This stage doesn't happen on the first time the page is accessed, it's a postback-only stage).
LoadPostData phase is when the data that has been posted to the server (by submitting the form) is loaded into controls. This stage is barely known to beginner ASP.NET developers, because they assume that all "state preservation" that is automatically enforced by ASP.NET engine comes from the magical Viewstate.
NOTE: If you are really serious about this, you can learn A LOT from this guy here: Understanding ASP.NET View State
What you need to remember from all the above now is that: in order for your dynamically generated controls to "have" their data "glued" together into the control's state after submitting the form by clicking this button Then I would have a button they click that would save the textbox values into the database., you need to add the controls to the page at each round-trip to the server.
The recommended way of doing so is in the Page_Init, because it comes before the LoadViewsate and LoadPostData stages where the control's state is populated.
In your case though, you don't know how many controls to add until the user fills that information on the first form submission. So, you need to find a way to add the controls to the page each time the page loads after the user entered the number of desired controls.
NOTE: You could get away with adding the controls on the btnBookQty_Click and have their data preserved correctly, because ASP.NET "plays catch-up" on the controls, but that's beyond the scope and purpose of this answer.
Add a private field to act as a boolean flag and to indicate the number of controls to add.
Create a private method that add the controls into the page, taking as argument the number of controls to add.
Call that method from within the Page_Init event handler, only if the flag dictates that some fields must be added.
In btnBookQty's click event handler set the flag to the number provided by the user of the page, and...
Call the method to create the dynamically generated controls from within btnBookQty_Click.
Here's a template code of what you need. Notice how HowManyControls property is stored in the Session to "remember" that value across postbacks:
private int HowManyControls {
get
{
if (Session["HowManyControls"] == null) return 0;
else return (int)Session["HowManyControls"];
}
set
{
Session["HowManyControls"] = value;
}
}
protected void Page_Init(object sender, EventArgs e)
{
if (Page.Ispostback && HowManyControls > 0)
{
//generate the controls dynamically
GenerateControls(HowManyControls);
}
}
protected void btnBookQty_Click(object sender, EventArgs e)
{
//get the number of controls to generate dynamically from the user posted values
HowManyControls = Convert.ToInt32(TextBox1.Text);
//generate the controls dynamically
GenerateControls(HowManyControls);
}
protected void btnSaveToDatabase_Click(object sender, EventArgs e)
{
//iterate on the control's collection in pnlBook object.
for (int i = 1; i <= HowManyControls; i++)
{
//save those value to database accessing to the control's properties as you'd regularly do:
TextBox tb = (TextBox)pnlBooks.FindControl("TextBoxTitle" + i.ToString());
TextBox tb2 = (TextBox)pnlBooks.FindControl("TextBoxAuthor" + i.ToString();
//store these values:
tb.Text;
tb2.Text;
}
}
private void GenerateControls(int count)
{
if (count == 0) { return; }
for (int i = 1; i <= count; i++)
{
TextBox tb = new TextBox();
TextBox tb2 = new TextBox();
tb.Text = "Book " + i.ToString() + " Title";
tb2.Text = "Book " + i.ToString() + " Author";
tb.ID = "TextBoxTitle" + i.ToString();
tb2.ID = "TextBoxAuthor" + i.ToString();
pnlBooks.Controls.Add(tb);
pnlBooks.Controls.Add(tb2);
pnlBooks.Controls.Add(new LiteralControl("<br />"));
}
}
EDIT
I had forgotten that ViewState is not available during Page_Init. I've now modified the answer to use Session instead.
When somebody says that "You need to keep track of the controls you create or recreate them" it means that you need to store them between postbacks.
In ASP.NET persistance can means Session variables, ViewStates and other means
See this link http://msdn.microsoft.com/en-us/magazine/cc300437.aspx
Create a list of the textboxes that you created and store it on a Session
private void CreateOrLoadTextBoxes(int numTextBoxes)
{
List<TextBox> lstControls ;
//if its the first time the controls need to be created
if(Session["lstTitleControls"] == null)
{
lstTbTitles = new List<TextBox>(numTextBoxes) ;
lstTbAuthors = new List<TextBox>(numTextBoxes) ;
//create the controls for Book Titles
for (int i = 1; i <= numTextBoxes; i++)
{
TextBox tb = new TextBox();
tb.Text = "Book " + i.ToString() + " Title";
tb.ID = "TextBoxTitle" + i.ToString();
lstTbTitles.Add(tb) ;
}
//Create the controls for Author
for (int i = 1; i <= numTextBoxes; i++)
{
TextBox tb2 = new TextBox();
tb2.Text = "Book " + i.ToString() + " Author";
tb2.ID = "TextBoxAuthor" + i.ToString();
lstTbAuthors.Add(tb2) ;
}
//store the created controls on ViewState asociated with the key "lstTitleControls" and "lstAuthorControls"
// each time you store or access a ViewState you a serialization or deserialization happens which is expensive/heavy
Session["lstTitleControls"] = lstTbTitles ;
Session["lstAuthorControls"] = lstTbAuthors ;
}
else
{
//restore the list of controls from the ViewState using the same key
lstTbTitles = (List<TextBox>) Session["lstTitleControls"];
lstTbAuthors = (List<TextBox>) Session["lstAuthorControls"];
numTextBoxes = lstTbTitles.Count() ;
}
//at this moment lstTbTitles and lstTbAuthors has a list of the controls that were just created or recovered from the ViewState
//now add the controls to the page
for (int i = 1; i <= numTextBoxes; i++)
{
pnlBooks.Controls.Add(lstTbTitles[i]);
pnlBooks.Controls.Add(lstTbAuthors[i]);
pnlBooks.Controls.Add(new LiteralControl("<br />"));
}
}
protected void Page_Load(object sender, EventArgs e)
{
CreateOrLoadTextBoxes(10) ;
}
As you have noticed I am calling the CreateOrLoadTextBoxes with a fixed value of 10
Is up to you to chane this code to take the value from the text box and call this as needed

rangevalidator c# how to use later in code

I created a range validator and would like to trigger it once the submit button was clicked.
RangeValidator rv_tbAbsenceDay = new RangeValidator();
rv_tbAbsenceDay.ID = "rv_tbAbsenceDay" + tbAbsenceDay.ID;
rv_tbAbsenceDay.ControlToValidate = tbAbsenceDay.ID;
rv_tbAbsenceDay.EnableClientScript = true;
rv_tbAbsenceDay.Display = ValidatorDisplay.Dynamic;
rv_tbAbsenceDay.MinimumValue = DateTime.Now.AddMonths(-6).ToString("d");
rv_tbAbsenceDay.MaximumValue = DateTime.Now.ToString("d");
rv_tbAbsenceDay.ErrorMessage = "Date cannot be older than 6 months and not in the future.";
rv_tbAbsenceDay.SetFocusOnError = true;
plcMyStaff.Controls.Add(rv_tbAbsenceDay);
plcMyStaff is a placeholder.
<asp:PlaceHolder ID="plcMyStaff" runat="server"></asp:PlaceHolder>
How do I get hold of the created range validator to trigger it i.e. rv.validate(); ?
I have tried this:
protected void MarkAsSick_Command(Object sender, CommandEventArgs e)
{
DropDownList tempddlReason = (DropDownList)plcMyStaff.FindControl("ddlReason" + e.CommandArgument.ToString());
TextBox temptbAbsenceDay = (TextBox)plcMyStaff.FindControl("tbAbsenceDay" + e.CommandArgument.ToString());
TextBox temptbLastDayWorked = (TextBox)plcMyStaff.FindControl("tbLastDayWorked" + e.CommandArgument.ToString());
RangeValidator temprv_tbAbsenceDay = (RangeValidator)plcMyStaff.FindControl("rv_tbAbsenceDay" + e.CommandArgument.ToString());
temprv_tbAbsenceDay.validate();
...
Hope you can help me.
thanks,
Andy
First off to debug this I would suggest examining the plcMyStaff object in which you are adding the control to see if it does in fact contain the control you wish to access.
You should be able to retrieve it from the Page object that your webform inherits.
Page.FindControl();
// Or you can Iterate through each control to see what the control is called and test for the name you want
foreach (var control in Page.Controls)
{
}

How to set dynamic parameter values to custom control from web page

I have one image button in the custom control like below.
public string SearchTableName = string.Empty;
public string SearchColumnName = string.Empty;
public string SiteURL = string.Empty;
ImageButton _imgbtn;
protected override void OnInit(EventArgs e)
{
_imgbtn = new ImageButton();
_imgbtn.ImageUrl = ImageURL;
_imgbtn.OnClientClick = "ShowSearchBox('" + SiteURL +"/_layouts/CustomSearch/SearchPage/Searchpage.aspx?table_name=" + SearchTableName + " &column_name=" + SearchColumnName + "')";
}
On Clicking of the image button I want to migrate to the another window which is a popup. For this I written a javascript function. I am setting the SearchTableName and SearchColumnName in the web page in which we are consuming this custom control like below. Before consuming I registered this control in web page with register tag.
<ncc:SearchControl runat="server" ID="txtSearchControl" /> In code behind file of this webpage I am using following code to set the values.
protected void Page_Load(object sender, EventArgs e)
{
txtSearchControl.ImageURL = "_layouts/Images/settingsicon.gif";
txtSearchControl.SearchTableName = "Employees";
txtSearchControl.SearchColumnName = "LastName";
txtSearchControl.SiteURL = "http://Sp2010:8787";
}
Now coming to the problem, when I click the image button the SearchTableName and SearchColumnName values are not coming. I think I am calling OnClientClick function, thats why the values are not being set. But how to set the values for the custom control based on the values setting in the webpage. If I use the Click function will it serve my purpose? If so, how to call that javascript function from this click event.
Finally got solution. I am initializing the values in the page init method in the custom control. Thats why the values i am setting in the visual webpart page are not being captured. Now I changed the initializing the values in CreateChildControl method. Now it works perfectly. Thank you.

ASP.Net rapid button click to add controls in UpdatePanel creates conccurency issue

When I click on a button and add a control to a Placeholder inside an UpdatePanel, everything is fine, except when I click really quickly several times and then get an error message like the following:
'Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: Multiple controls with the same ID 'VehicleRegistrationEnhancedTextBox3_Label' were found. FindControl requires that controls have unique IDs.' when calling method: [nsIDOMEventListener::handleEvent]
[Break On This Error]
I save an integer in a hidden field, to create unique Ids, when I click really fast, the method executes several times, but the count value has not yet updated. I tried using the C# lock keyword, but that did nothing.
The code is below:
protected void AddVehicleButton_Click(object sender, EventArgs e)
{
lock (this)
{
int count = Convert.ToInt32(VehicleRegistrationCountHiddenField.Value);
var TBId = "VehicleRegistrationEnhancedTextBox" + count;
IList<Panel> oldPanels = (IList<Panel>)Session["VehiclePanels"] ?? new List<Panel>();
//Seperator
Literal hr = new Literal { Text = "<hr/>" };
//RemoveSpan
Literal span = new Literal() { Text = "<span class=\"RemoveVehicleRegistration\">X</span>" };
//Crop
Control uc = LoadControl("~/Controls/ImageUploadAndCrop/ImageUploadAndCrop.ascx");
uc.ID = "VehicleRegistrationImageUploadAndCrop" + count;
//Vehicle Registration
Label vehicleRegistration = new Label
{
ID = TBId + "_Label",
AssociatedControlID = TBId,
Text = "Vehicle Registration:"
};
EnhancedTextBox vehicleTypeTextBox = new EnhancedTextBox
{
ID = TBId,
Required = true,
RequiredErrorText = "Vehicle Registration is a required field."
};
//Add new controls to the form
Panel newPanel = new Panel();
newPanel.Controls.Add(hr);
newPanel.Controls.Add(span);
newPanel.Controls.Add(vehicleRegistration);
newPanel.Controls.Add(uc);
newPanel.Controls.Add(vehicleTypeTextBox);
AddVehiclePlaceholder.Controls.Add(newPanel);
//Increment the ID count
count++;
VehicleRegistrationCountHiddenField.Value = count.ToString();
//Save the panel to the Session.
oldPanels.Add(newPanel);
Session["VehiclePanels"] = oldPanels;
//Go back to the same wizard step.
ShowStep2HiddenField.Value = "true";
ShowStep3HiddenField.Value = "false";
}
}
The problem is you are kicking of several postbacks with the same request, then the last response is what's updating your update panel div, causing your issue. One possible solution is to include some javascript to disable your button on click.
<asp:Button ID="myUpdatePanelPostBackButton" runat="server" OnClientClick="this.disabled=true; return true;" Text="Submit" />
Assuming your button is within your UpdatePanel, when the update panel comes back, the button will be re-enabled.
Disabled button will not cause a PostBack. So if you only disable button in OnClientClick, a PostBack will not occur.
Try UseSubmitBehavior="false", it means "anyway cause postback".
<asp:Button runat="server" ID="BtnSubmit"
OnClientClick="this.disabled = true; this.value = 'Submitting...';"
UseSubmitBehavior="false"
OnClick="BtnSubmit_Click"
Text="Submit Me!" />
Refer this blog , it's useful for you.
http://encosia.com/disable-a-button-control-during-postback/

Why can't I update HiddenFields on PostBack?

This is my code :
private string[] MesiSelezionati;
protected void Page_Load(object sender, EventArgs e)
{
MesiSelezionati = new string[] { "2", "4" };
UpdateMesi();
}
override protected void OnInit(EventArgs e)
{
for (int i = 1; i <= 12; i++)
{
HtmlGenericControl meseItem = new HtmlGenericControl("a") { InnerHtml = "mese" };
meseItem.Attributes.Add("href", "javascript:void(0);");
HiddenField hf = new HiddenField();
hf.Value = "0";
hf.ID = "idMese_" + i.ToString();
meseItem.Controls.Add(hf);
panelMesi.Controls.Add(meseItem);
}
base.OnInit(e);
}
private void UpdateMesi()
{
foreach (HtmlGenericControl a in panelMesi.Controls.OfType<HtmlGenericControl>())
{
HiddenField hf = a.Controls.OfType<HiddenField>().LastOrDefault();
if (MesiSelezionati.Contains(hf.ID.Split('_').LastOrDefault()))
{
hf.Value = "1";
a.Attributes.Add("class", "box-ricerca-avanzata-item link-box selected");
}
}
}
When I call the page, all is ok! The problem is when I call the same page (so, postback) thanks to a asp:LinkButton. I get a System.NullReferenceException on if (MesiSelezionati.Contains(hf.ID.Split('_').LastOrDefault())).
Seems that the HiddenField of the 2° and 4° link (which corrispond to the position at MesiSelezionati = new string[] { "2", "4" };) are null. Why? And how can I fix it?
EDIT : code for Mark M
HtmlGenericControl optionBox = new HtmlGenericControl("div");
optionBox.Attributes["class"] = "option-box";
HtmlGenericControl optionBoxItem = new HtmlGenericControl("a") { InnerHtml = " " };
optionBoxItem.Attributes.Add("href", "javascript:void(0);");
optionBoxItem.Attributes.Add("class", "option-box-item");
HtmlGenericControl optionBoxTesto = new HtmlGenericControl("a") { InnerText = Categoria.Categoria };
optionBoxTesto.Attributes.Add("href", "javascript:void(0);");
optionBoxTesto.Attributes.Add("class", "option-box-testo");
HiddenField hf = new HiddenField();
hf.Value = "0";
hf.ID = "categoria_" + Categoria.UniqueID;
optionBox.Controls.Add(optionBoxItem);
optionBox.Controls.Add(optionBoxTesto);
optionBox.Controls.Add(hf);
panelCategorieGuida.Controls.Add(optionBox);
You can update hidden fields on postback, just not before Load. When executing OnInit, the controls have not been populated using the request & view state values. Your updates are being overwritten.
EDIT: I found the root cause of your issue & learned something in the process.
You set the InnerHtml property of the anchor tag (InnerHtml = "mese") in the OnInit method. Under the covers this assignment is ViewState["innerhtml"] = "mese".
You assign a css class to the anchor after ViewState tracking has begun, so the ViewState restoration machinery will apply to this control on postback.
When you postback the anchor tags with added css classes will be subject to HtmlContainerControl.LoadViewState (which occurs between InitComplete and PreLoad). If the LoadViewState method detects that ViewState["innerhtml"] has a value it wipes out all of the control's child controls (calling Controls.Clear()) and creates a LiteralControl to contain the innerhtml value, adding it as the sole child control.
Basically this means that you cannot set both the InnerHtml property and add any controls to a descendant of HtmlContainerControl if that control will ever be subject to ViewState tracking.
To fix your example; instead of setting InnerHtml to add the link text, create a LiteralControl with the desired text and add it to the anchor's child control collection.
is your link button in some separate panel control? Can it be the case that you are doing partial postback, with AJAX? Sorry for answering with the question.

Categories

Resources