View state vs Hidden field in asp.net - asp.net

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

Related

Problem getting list box items added through jquery in code behind

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];

hidden field usage

what are the possible usage of hiddden field control of VWD in asp.net page
Hidden input fields could be added to a form in order to pass some value when the form is submitted that the user doesn't see and cannot modify using the application interface. They could be useful when you want to persist some values across multiple requests. It's true that in a standard ASP.NET WebForms application their value is quite limited as you already have hidden values holding the View State allowing you to persist values across requests.
Hidden fields can be used to transfer data back to the server from the front-end and also sending data from server to browser. For e.g. you've written a javascript function that needs to do something if the value of a field is x, then you can always create a hidden field and set its value from server; your javascript can pick the value from this and do whatever it wants to do. It's just like a normal text field, the only difference is that it isn't visible on the page.
Asp.Net internally uses hidden fields to send view state data too. When your .aspx page has been rendered, view its source and you'll see asp.net has automatically created a few hidden fields for its own use.
In Asp.Net architecture it is used as 1 of the 8 (client-side) State Management mechanisms.

Two ASP.NET Postback related questions

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.

How to retrieve data from dynamically added textboxes?

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

Legacy ASP.NET 1.1 with jQuery integration problem

I am working on a legacy web application written in VB.NET for ASP.NET 1.1. One particular page has a form with a number of fields. In response to a drop-down box changing value, I am clearing a number of fields, resetting a number of drop-down boxes to the first option, and setting them all to "disabled" in the UI. To do this, I'm using jQuery. I add a CSS class to all of these fields, and then my jQuery selector is something like the following: $("*.my-css-class"). Here's some sample code to explain.
var fields = $("*.fields");
if (some_condition) {
fields.val("");
fields.attr("selectedIndex", 0);
fields.attr("disabled", "disabled");
}
The UI updates as expected in response to the above js code, but when I post back the page in response to a button click, the original values still persist on the server-side related to these controls. For instance, txtSomething is one of the fields with a CSS class "fields" (so it will get selected by the above jQuery selector). The user types "1234" in this text box and submits the form. Either the same page is posted back to itself retaining its values, or I return to this page and prepopulate the values on the server-side (for example, the user clicks an Edit button on a summary page), so the control txtSomething is initialized on the client with the value "1234". My jQuery code clears the value as far as the user sees it in the UI, and then the user clicks a submit button. If I interrogate the value with a jQuery selector, the value of this field is an empty string. When the page is posted back and I'm stepping through the code (or doing something with the value of this control), it is still "1234".
A very important point to make is that these values are sent back to the browser after being submitted once. So, picture a form being submitted, or any case where these values are bound or set on the server-side and outputted to the browser pre-populated (as opposed to being output to the browser with default or empty values). If I load the page as default (empty text boxes), enter some text, and then trigger the js function to clear these fields, the value I typed never makes it to the server.
why do you need to disable those fields? Disabling controls can make them not post values to the server ... at least that is what happens when an asp.net control is disabled server side.
Update 1: couldn't take having the doubt if it was only server side, so I looked it up :) http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1 ... "In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.", so I was right, even when disabling it client side it won't post the value

Resources