Question 1)
I have a control to which I add an attribute from the server side by using a sentence like:
ControlName.Attributes.Add("myTestAttribute", "")
From the client side I modify the value of this attribute by using the Javascript function:
Document.getElementById(ControlName).setAttribute("myTestAttribute", “Hello Server!!”);
My problem is that when I try to acces to the attribute value on the Postback treatment function the attribute is empty.
Am I missing some step?
Question 2)
Is it possible to obtain the full HTML code of the page in the server side from inside a Postback treatment function?
If javascript modifies elemants on a page, they will not be visible to the server. When a postback occurs, the only data that is available to the server is the data that is sent in the form on the page.
ASP.net handles standard form elements such as textboxes, drop down lists etc. by putting their values into a hidden field called viewstate (this is normally encoded so cannot be read directly).
If you want page elements modified by javascript to be visible to the server, you can write new hidden form elements and retrieve them from the Request[string name] array.
Put that attribute add code in Page_Init
Nope
In response to question 2, you could persist the status of these attributes in the viewstate if you wanted to know their values after a postback.
Related
I have a web page and a modal dialog page. On clicking the save button in the show modal dialog. closes the window and returns a value. Now when the
control reaches the JavaScript function of the parent window . I wnt to perform some database operation on the basis of this returned ID.
I am using the following approach to utilize this returned value.
Keeping it in the hidden field and populating the returned value in hidden control.
keeping a hidden button in the parent window, performing the click event when control comes back to JavaScript function of the parent page. Thus in the server side button handler get the value from hidden field and perform database operation on the basis of returned value.
Is this approach fine. Or I can get rid of hidden field
That's not terribly bad provided the ID returned is not sensitive information that someone can use to modify a record that doesn't belong to him. One can perfectly manipulate this ID on the client side for any other ID and have your logic update a different record from what you intended.
If all you are doing is calling a server side method passing this ID; why don't you do the whole update from the pop-window itself (at that point you already know the ID)?
If the parent window (page) is meant to be updated; you can just perform a normal refresh of the page (ie. use window.location to redirect the user to the same page so he can see the update or use Response.Redirect to the same page.)
What you're probably looking for is called AJAX. With AJAX you can communicate with your web server from within your JavaScript code directly. No HTML form posts are required then. You might want to look at frameworks like JQuery. These have easy implementations (cross browser wrappers) to send HTTP requests via AJAX.
Note: I just noticed, you are using ASP.NET. Take a look at ASP.Net AJAX Page Methods.
I have a asp.net list box control in which i populate items using Jquery by using some code like ..
$("#MylistBox").append("<option value='somevalue'>Someitem</option>
dynamically .
but in code behind when i use
MylistBox.Items is always showing Count 0 no matter how much items add.
Can anybody help me with this?
Without knowing the actual scenario... I am assuming your goal is actually to get the dynamically added items either by iterating over them or something else...
Any dynamically added DOM element that is done on the client side using JavaScript / jQuery, will not be reflected automatically to the server side. You will need to serialize them in a different way and push them back to the server side during postback. One way you can do this is by serializing all the Options of the Select element in a hidden input. You can mark the hidden input as runat=server if you wish to make it easier for you to access, otherwise use Request.Form["...hidden input NAME attribute here... NOT ID..."] to get the value out. After you get it, you can do whatever you want with the values.
I imagine your hidden input should have some value like: "1:First Value,2:Second Value,3:...". Just do some string manipulation to split them up and iterate over them.
The code behind will only be aware of items that were added to the Listbox object when it was created on the server. These items will be held in ViewState and repopulated during postback.
Therefore items created dynamically on the client won't be visible to the server side code.
If you need to get the selected value in the server side code then you are going to need to query the Request.Form["<Listbox client id>"] value during the postback.
If you need to retrieve all items added to a list box on the client I would suggest adding them all to a hidden field value as a delimited array of strings and again retrieving them using Request.Form["<hidden field id>"].
string values = Request.Form[ListBox_SelectedSubject.UniqueID];
How can we take decision for viewstate and hidden field in ASP.NET.
In my case i am using page cross post back and by using public properties of first page i am accessing them in second aspx page.
After getting public variable in second aspx page i need to access those value in second page but as soon as i do postback in second page, i am not able to find those value.
Hence to solve this issue i have two solution either use viewstate in second page or using hidden field in second page.
I am not able to decide which one should i use?
The approach is quite the same. Only difference should be the size of stored info (viewstate is using [sometimes encrypted] base64 while hidden fields use plain text unless you encode them yourself), and viewstate allows you to make sure the data was not tampered with thanks to the default validation it has in place.
If the data is small and you want to manipulate the value based on some client-side behaviour, hidden field will be useful.
Difference between view state and a hidden field in asp.net
http://royalarun.blogspot.in/2012/03/difference-between-view-state-and.html
Both are used to store the value during the postback in asp.net , but
In View state - not able to change the value by Client side code i.e java script.
Hidden field - possible to change value by Client side code.
In View state - You can store more than one value like Datatable and Dataset
Hidden field - You can store more than one value in hidden field,by serialized it.
View state data is encrypted and Hidden field is not encrypted
I need to develop a page which has 2 dropdownlist.
Options of dropdownlist 2 are based on selection of dropdownlist 1.
I have 2 methods to change the dropdownlist 2. What will you choose?
1:
Postback when users select dropdownlist 1 and change dropdownlist 2.
Pros:
Can use the postback feature, can use the asp.net validator
Cons:
Need to communicate with server (more traffic)
Users will see the page loading in the status bar.
2:
Get all the data (not very much data) in a JSON object when loading the page and change the dropdownlist 2 using javascript.
Pros:
Don't need to communicate with server(less traffic)
Cons:
Can't use the postback feature and validator and more troublesome to write server validation.
Also, I usually write the JSON object to the page as follows:
var locations = <asp:Literal runat="server" id="litLocation" text="[]" />
And then set the "litLocation" in page_load after the data is processed by datacontractjsonserializer.
Do you do it in the same way?
I prefer the second option, no need to reload the whole page just to refresh one dropdown list. I'd also do the client side dev in jQuery, much easier. You can do the client side validation for the change event of the first dropdown in jQuery as well, and keep the form submit validation in ASP.NET.
Have a look at the selectChain plugin for jQuery (demo's etc here).
Why not have your javascript call the server when the select box is clicked on, using a GET method, and fill in the select box, using json as the response, then, when an option is picked then fill in the second select box with another ajax request.
This would be scalable, in that if you want to add more options you just change the server, and everything is centralized.
You will need to validate when the form is submitted anyway, as it is possible to change a value of a form to something illegal using some debugging tools, such as Firebug, so never trust anything from a webpage until you have validated it.
So, no point worrying about the validation until the form is actually submitted.
Im adding textboxes (not a fixed number of textboxes) dynamically to a form on ASP.NET page, how do i read back data from these textboxes?
Assuming you're wanting to access the controls on the postback you'd probably re-create the dynamic controls exactly as they were created on the initial load, then use the page's FindControls method to find the controls. It would probably help to create the textboxes with IDs like Textbox1, Textbox2, etc.
Look at Request.Params and extract them from there. You will, of course, have to give them ids to be able to tell them apart.
From all the ASP.NET apps I've worked with, .NET likes to use the following algorithm when generating the Id for server controls:
ctl00$cphBody$[ControlID]
Try using this algorithm when accessing your data from the dynamically generated textboxes.
When you add them you should be giving them names/ids, and you can use those to reference them.
If not, walk your DOM in javascript to find them inside the form you made - they'll be in the same order you inserted them.
Lastly, they're all available as post/get inputs to your page, so you should be able to look at them all as long as you assigned them different names.
-Adam
When creating textboxes dynamically (presumably using JavaScript, but same goes for ASP.NET controls) give them names in a specific pattern. The one you will be able to recognize later.
On server-side, in any event handler occurring after Page_Init you can iterate through Request.Form collection.
Do not be tempted to use Request.Param because it can be used to apply cross-site request forgery on your application (an attacker could lure user into issuing a GET request which your application would interpret the same as it would interpret a POST one, which is usually not a good thing).
If you are adding dynamic ASP.NET controls (in Page_Render for example) you can also reconstruct controls and use their properties.
You can use FindControl and pass the textbox ID to get an instance of the textbox when post back. The Text property contains the data, given that we are at page load stage or later in the cycle.
When adding dynamic controls, override the CreateChildControls method and add the dynamic controls to control hierarchy at this stage of the cycle.
Remember that in ASP.Net, every postback is a new instance of your class. If you created these controls during a previous postback or on the first view then they were garbage collected with the rest of that previous instance. So to use the controls in this new instance, you need to create them again. If you need the state information loaded for those controls (including any value entered by the user), you also need to create before the viewstate is loaded, meaning you do it during the Init event, rather than the load event.
To create dynamic controls, I would usually use a ASP.NET PlaceHolder Control and add the dynamic controls to this container.
I would give each dynamic control an ID.
You can then subsequently use FindControl on the PlaceHolder to access the dynamic controls.
I say "dynamic controls" to mean controls you add at run-time