Find what Elements were added by Javascript - c#

I have got an ASP-Site, which enables the user to Add Label-Elements. I don’t know how many Labels where added or which ID they have. I know only, they will be within the Panel pnl_Added. After the user has added all his labels, he pushes a Send-Button for Update.
So, now I am at my Server, awaiting this postback, but I don’t know where, when and how to find out, which Elements were Added to pnl_Added. Can somebody help me?
I have tried something like that:
protected void Page_Load(object sender, EventArgs e)
{
[...]
for (int i = 0; i < pnl_Added.Controls.Count; i++)
{
[...]
}
[...]
}
But I think it is too late because of the loaded ViewState? Is that possible?
I am working with VS 2013, ASP c#, with the .Net Framework 4.

On server, controls tree doesn't created from actual client HTML. Actually, server doesn't know anything about client HTML besides input tags values in scope of submitted form. In general, all controls available in Page_Load method, created on server side from aspx file markup.
To implement your scenario, you need to add hidden field for each label, added from client and save label's inner text into hidden field's value. Then you'll can get these labels texts as below:
var labels = Request.Form["hiddenField's name"] as string[];

You should go one lever deeper and take the added elements from Request variable, because the control pnl_Added doesn't know about them as there was no postback.
Something like this:
Request.Form["field_id"]
I suggest to run the page in debug mode, review Request.Form collection and find what you need. You should see your label elements there.

Related

Asp.Net data attributes dynamically updated through JS/jQuery but the updated attributes aren't updated when retrieved through code behind

I have an aspx page of images that, when selected, a popup appears prompting for various information tid bits that I then store the information as data attributes on hidden labels through use of jQuery (i.e. data-id="####", data-difficulty="###", etc.). I acknowledge that this isn't the best way to do it necessarily but I've tried other things (see below) and nothing has worked yet.
I've been attempting, and to no avail, to retrieve the dynamically updated data attributes so the various items can be stored to my local ms sql database. The updating of the attributes works perfectly in that I can view the items being updated properly in Chrome's developer tools. Despite this when I try to pull the same attributes I can see as being updated I'm unable to retrieve the updated values in the code behind and keep getting back the initial values (generally an empty string "").
Here's the implementation on the aspx page:
<asp:Label runat="server" ID="lblSelection" data-id="" data-count="" data-price="" data-difficulty="" CssClass="selected-items" />
and here's the relevant method being called when the "Submit" button is clicked further down on the same page:
protected void SubmitClicked(object sender, EventArgs e)
{
var currentID = lblSelection.Attributes["data-id"];
var currentCount = lblSelection.Attributes["data-count"];
var currentPrice = lblSelection.Attributes["data-price"];
var currentDifficulty = lblSelection.Attributes["data-difficulty"];
if (currentID == null || currentID == "")
{
// stop and throw an informative message to the user
}else{
// keep processing ...
}
}
The trouble is that when I run the project in debug mode and inspect those elements (again, making sure that I can visually see that the attributes are actually updated in the developer tools) they're all the initial value of "". My only guess is that there's some kind of post back issue but I wouldn't think that would happen until my method had been called and fully processed. As a note, I'm populating the images onto the page and updating their attributes already through a sql call based on the id of the item:
<img runat="server" src="" data-id="12345" />
The initial loading all works perfectly so I can clearly set the properties from the code behind fine. For whatever reason though I am unable to pick up the updated attribute values in the code behind after the jQuery updates the label's attributes (following some clicking and whatnot). Any tips or thoughts on this would be greatly appreciated.
What you are trying to do cannot work because:
The value of custom attributes is not posted back to the server (as discussed here).
Even if you set the text of the Label in client code, it would also not be available in the Text property in code-behind. A Label is rendered as a span element in the page, and the content of that type of element is not posted back to the server.
A nice list of properties included in a postback is given in this topic: Which values browser collects as a postback data?
As suggested by mshsayem, you should use HiddenFields. If, for some reason, you want to do it differently, you could use hidden TextBoxes, set their value in client code, and retrieve it with the Text property in code-behind. In other words: HiddenFields are not the only controls for which a value set in client-code can be retrieved in code-behind (but they are the obvious choice if the control is not to be displayed).

Possible to have dynamic content with accessable controls in asp.net/C#

I really hope that someone can help, pointing me in the right direction. I'm still new to the more advanced features of asp.net / C#.
What i need is a div, in that div i would want some informations from the database. furthermore i want a textbox with a number and an arrow up and down to increase/decrease the amount in the textbox. And at last a button outside the div to submit the value.
Now the tricky part (for me), is that one div is not enough, I need one div for each "person" in the database. i can easily make that, but.. if i add it dynamically from the .aspx.cs file i am not able to access the value like : textbox1.text; because textbox1 does not exist in the code before it is created.
I have looked at listview and a repeater, but those seems more like they're for making lists, and i need more than that, as i need some functionally too.
The way i would do it now is to add the div by innerhtml. and then adjust the amount by a for loop which also inserts the information from the database which i got in an array. But as said, that doesn't really do the trick when i need to access the textbox and stuff.
Thanks in advance for just looking at it.
EDIT:
I'm not looking for at complete solution, i just want some directions.
I will asume by your post description that by asp.net you mean webForms. If you're new on asp.net development, you have to know that there are different development, in the past (but still very commonly used) you would use WebForms, now at days the trends are using asp.net MVC framework.
now back to your question:
in asp.net WebForms, you have your code defined in two sides: your markup (HTML code normally in a .aspx file) and your code-behind (c# or vb code normally in a .aspx.cs or .aspx.vb).
what I would suggest you to do, is to add your logic for retrieving data from your database in your page_load() function of your code-behind, with this data you would normally use a loop to read all your results and for each result you would create your div with your textbox inside (the trick is using native .net framework classes instead of inserting the HTML directly). a simple example:
protected void Page_Load(object sender, EventArgs e)
{
string[] personsIDs; //<-- this came from your database
Dictionary<string, TextBox> textBoxes = new Dictionary<string, TextBox>();
foreach(string personID in personsIDs)
{
TextBox personTextBox = new TextBox();
personTextBox.ID = "textBox"+personID;
textBoxes.add("textbox"+personID, personTextBox);
}
I explain you:
first, I'm assuming there is an array of the personsIDs, so I created a dictionary (key -> value object) using strings as keys and TextBoxes as values.
then using a foreach I read all the personsID's, and for each one of them I create a new TextBox UIControl and add it to the dictionary using the personID as key. I also added its ID property as "textbox"+PersonID.
this way you can access your textboxes from code-behind by using your dictionary:
textBoxes["textbox"+personID] //(e.g: textBoxes['textBox11'])
but also, since your textBox.ID is equal to textbox+personID, you can also reference it after page has been rendered (e.g. using javascript).
now to add this controlers to your page, just use a container(UIControl) that already exists on your page, and use
container.controls.add(textbox);
this process can be expanded for extra elements, for instance:
1.- have a main placeholder already defined in your page:
<asp:Panel ID= "Panel1" runat = "server">
2.- in your code-behind for each person create a new panel and add all the elements you want inside that panel:
//this goes inside your foreach
Panel innerPanel = new Panel();
TextBox textBox = new TextBox();
Label label = new Label();
innerPanel.controls.add(textbox);
innerPanel.controls.add(label);
////
finally add your innerPanels in to your main panel:
panel1.controls.add(innerPanel);
so there you go, that's basically the idea, hope this helps.

Disable postback of certain properties of Telerik RadEditor control

We have a page with Telerik RadEditor on a tab strip. There are scenarios when RadEditor contains a lot of html and when doing a post back in order to switch the tab, all its contents is being post back to the server. This results in gigantic performance loss (there are times when post backs are sending tens of MiB of data).
Is it possible to tweak RadEditor in such a way that it does not send its contents over to server on postbacks? Our code-behind does not rely on RadEditors Content property accessor (does not read its content explicitly), only its mutator (its contents are set from within the control's code-behind).
Is it even possible to do such things with any of Telerik controls and if it is, then how do we achieve such result?
It's worth pointing out that we use relatively old Telerik UI version (2013.2.611.35) and we can't switch to a newer version at the moment.
Thank you in advance.
Consider using the ContentUrl of the PageViews. This will let you load separate pages in iframes, so they will postback independently of the main page. Thus, you can have a standalone page with the editor and standalone pages for your other tabs.
On the possibility to exclude something from the POST request - I don't know of a way to do this, as it is not supposed to happen. The whole point is to transfer the current page state to the server.
Another option you may consider is using AJAX and the PageRequestManager's beingRequest event to try to blank out the editor. I have not tried it and I do not know whether it will actually work out, since so much data may simply be too much for the JS engine to process before the postback begins. Here is a bit of code that illustrates the idea:
var currContent = null;
function BeginRequestHandler(sender, args) {
var editor = $find("<%=RadEditor1.ClientID%>");
currContent = editor.get_html(true);
editor.set_html("");
}
function EndRequestHandler(sender, args) {
var editor = $find("<%=RadEditor1.ClientID%>");
editor.set_html(currContent);
currContent = null;
}
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

c# not recognizing html div element

best to show this by code example:
html
<div runat="server" id="PI"> </div>
c#
protected void addNewProject_Click(object sender, EventArgs e)
{
PI.attributes.add("z-index", "0");
}
basically gives me an error saying "the name PI does not exist int he current context."
Any idea why it says that?
Make sure that your .designer.* file has been updated with a variable for PI. Some source control systems lock the file and prevent Visual Studio from automatically updating the file.
If the variable hasn't been created for you, you can always go back to your .designer file and add the new variable yourself. Just follow the patter for your other ASP.NET controls.
You're looking for a partial class with the same name as your code behind class.
This SO question addresses your issue as well.
I found an alternative solution, instead of making the image switch z-indexes, I am making the asp.net panel switch z-indexes. For some reason when I try to declare my object in designer.cs file...it registers in code behind. This is good, however right when I test it out on a web-browser, the designer file auto-regenerates and gets rid of it again. So instead of playing around with the html controls I played around with what I know works and used the asp.net panel controls.
I always declare them in my codebehind file, something like this:
var myDiv = new HtmlGenericControl("div");
Then you just treat it the same as any other control on your page.

Asp.net controls not updating after a postback

I'm writing code to read data from asp controls to update records in a database. I've been debugging the last day and I've tracked it back to something that I ought to have noticed before.
The code first populates the controls with the existing values from the database.
When I click SAVE, it should read the current values from the controls and save with those.
Unfortunately, what it's actually doing is using the values of the controls before a change was made to them. It's not seeing the change to the controls.
Here's a sample:
<asp:TextBox ID="OtherCourseName_5" runat="server"></asp:TextBox>
Here's the corresponding behind code in the btnSave_onClick() function:
int object_number=5;
string other_course_name_string
= "OtherCourseName_" + object_number.ToString().Trim();
TextBox ocn = utilities
.utils
.FindControlRecursive(this.Master, other_course_name_string) as TextBox;
I'm using the FindControlRecursive() I found somewhere on the web. It works, I'm sure, but just in case, I tried to address the control directly as OtherCourseName_5.Text.
Even if I just display the value in OtherCourseName_5.Text, it gives the original value.
I use this same page for both entering new data and for editing data. It works fine when I enter the data. That is, it correctly sees that the TextBox control has changed from empty to having data. It's only when I invoke the edit function on the page (by passing edit=true). I invoke it this way by adding the switch edit=true as a query string (the program correctly reads that switch, gets to the appropriate area of code, prints out all the correct values for everything - except the contents of the controls!).
The page is far too complicated to post the entire thing. I've tried to convey the essential details. It's entirely possible that I've made a simple coding error, but it's seeming more a possibility that I fundamentally misunderstand how pages are processed.
Is there anything known that can make it seem as though the value of a control has not been changed?
Note 1: I thought perhaps I had to go to another field after I entered the data, but I tried that and it's still a problem.
Note 2: I'm using both TextBox and DropDownList controls and have the same problem with both.
Note 3: These controls are on a panel and the page is using a SiteMaster. I haven't had any problem with that and don't think the problem is there, but I'm down to questioning the laws of the physics at this point.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//populate controls with data from database
}
}
When you do a postback before the postback handler is evaluated the PageLoad event is raised
so if you don't avoid to rebind your control they will be loaded with the values from the database. And then the postback event will save them to db
Asp.net Page Lifecycle
(source: microsoft.com)

Categories

Resources