How I can deactivate ViewState without Control problems - c#

I wrote a ASP.NET Application and it run in IIS7 of a Server. If I open this webform in my Browser and show me the Sitecode I see this...
I have many Controls how Buttons,Labels,TextBoxes and a ListView. I try to deactivate ViewState in the web.config but if I deactivate this my Application don't run correctly. What can I do?

Deactivate only the controls that not need the viewstate.
To do that you need to understand what the viewstate is.
Viewstate is where the page save and remember the values of the controls to have them after a post back. Remember that, the viewstate is used after a post back.
So actually you have two times the same data, but only the viewstate is post back the previous data and code behind can be use that data.
So the main question is, what controls do you need to be remember what you have fill them in, or what controls need to remeber the previous state of them.
Lets see a simple Literal with EnableViewState on and off.
ViewState ON
<asp:Literal runat="server" EnableViewState="true" ID="txtLiterar">
Now if you place a text on this literal the text is also saved on viewstate and on code behind you can do that.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtLiterar.Text = "Hello There";
}
}
So after the post back the Literal still have its content, and you can avoid to fill it again, because the viewstate have it and automatically fills it again.
ViewState OFF
<asp:Literal runat="server" EnableViewState="false" ID="txtLiterar">
Now if you place a text on this literal the text is not saved on view state and on code behind you add it as.
protected void Page_Load(object sender, EventArgs e)
{
txtLiterar.Text = "Hello There";
}
So the different is that you need to always fill that control with data on every post.
Where the viewstate is needed most.
The most needed part of the viewstate is when you fill a dropdown list. There you have a databind and code behind need to remember the values to place on the SelectValue the correct one.
Its also needed on GridView and other controls like that because is keep the previous page and other information's when you paging your data.
So you can close on most of your controls the viewstate - on that controls that you can fill them again on every post back, and on that controls that not need to remeber the previous state.
More to read:
How to optimize class for viewstate
Determine size of ASP.NET page's viewstate before serving page
Limiting view state information on AJAX calls

Related

Losing values after refreshing button asp.net

I have the following project :
It's a page that on Page_Load it fills a TextBox named Email and a TextBox named UserName with a value obtained from asking a database.
Then there is this button, if the email is not null(user is not registered) it will let you register, otherwise it will let you change the email linked to your username.
The thing is, when trying to modify the email, doing an update query, the page preloads, taking the new value placed on Textbox Email the same that is retrieved from the database, making so it will never change.
I've tried to see if it executes the query and it does.
I've tried everything, keeping the variable on a hidden label, creating two different buttons with no luck as when it reloads the code those values are empty again.
I was thinking if I could keep the variable somehow that isn't cookies.
I think You know What is happening.. On every Post back the Page_Load event resetting your Textbox Value
Use IsPostBack to bind the value only on 1st load of page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//bind dropdown and fill textbox here
TxtName.Text = "Your values";
GetDropdowns();
}
}
I hope this will solve your issue
I totally agree with Kanis XXX, you can use IsPostBack to fill the values only at the start page, and not on other postbacks. In my experience, there are some other advices for your problems:
Using Viewstate, Session state,... to keep your working variable. You can have more detail here: https://kimphuc.wordpress.com/2009/10/18/the-difference-between-viewstate-sessionstate-cookies-and-cache-in-asp-net/
Try to use UpdatePanel, this could be useful in some cases, let you refresh or update data just a part of your page, not the whole page. https://msdn.microsoft.com/en-gb/library/bb398864%28v=vs.100%29.aspx

ListBox implements IPostBackDataHandler but why can't it maintain its state like a TextBox when EnableViewState is set to false?

In this post, Understanding ASP.NET View State, the author says this:
It is a common misconception among developers that view state is somehow responsible for having TextBoxes, CheckBoxes, DropDownLists, and other Web controls remember their values across postback. This is not the case, as the values are identified via posted back form field values, and assigned in the LoadPostData() method for those controls that implement IPostBackDataHandler.
So, when I disable view state for a TextBox, it still persists its text value across postback, which is correct based on the description above.
However, when I disable view state for a ListBox, which also implements IPostBackDataHandler, it does not persists its state in postbacks. For example, the code provided below is supposed to add duplicate items when a button (in the same webform) is clicked (with an empty event handler), but it does not.
Am I missing something here?
protected void Page_Load(object sender, EventArgs e)
{
lbox.Items.Add("1");
lbox.Items.Add("2");
lbox.Items.Add("3");
}
I think the answer can be found from the image below. (And as tested)
As you notice in Step 1, the value in lblMessage.Text is "Hello World!", without anything to Raise PostBack Event Stage, therefore the value is retained as is.
<asp:Label runat="server" ID="lblMessage"
Font-Name="Verdana" Text="Hello, World!"></asp:Label>
<br />
<asp:Button runat="server"
Text="Change Message" ID="btnSubmit"></asp:Button>
<br />
<asp:Button runat="server" Text="Empty Postback"></asp:Button>
And the code-behind class contains the following event handler for the
Button's Click event:
private void btnSubmit_Click(object sender, EventArgs e)
{
lblMessage.Text = "Goodbye, Everyone!";
}
Next then, for textboxes EVEN if you disable the view-state to a specific control / whole page, what's saved is the PostBack Event, thats why if you take a look at Step 3, the previous PostBack is loaded as part of Load View State Stage, which makes the "Hello World!" that's been Instantiated, overwritten.
This explanation BTW only applies for control events that does not use DataSource, other controls that requires DataSource seems implicitly defined in the doc.
In the sentences you quote, the word "values" refers specifically to the form field values posted by the browser to the server when the user submits the form. These values are defined by the HTML specification:
For a TextBox control, which is rendered as an <input type="text"> element, the browser posts the text entered in the text box. The TextBox control's IPostBackDataHandler implementation reads this value and assigns it to the Text property.
For a ListBox control, which is rendered as a <select> element, the browser posts the value of each selected <option>. (The browser does not post the entire list of <option> elements.) The ListBox control's IPostBackDataHandler implementation reads these values and selects/deselects each ListItem accordingly. (The implementation does not add any items.)
The important point is that the browser posts these values regardless of whether view state is enabled or disabled. Thus, even when view state is disabled, TextBox.Text and ListBox.SelectedValue will retain the user's input across postbacks.
However, anything else not normally posted by the browser (such as the list of options in a ListBox) requires view state to be enabled for it to be preserved across postbacks.

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)

Asp.net Hidden field not having value in code behind, but *is* retaining value after postbacks

In my ASCX, I have an asp.net hidden field defined as <asp:HiddenField ID="hdnNewAsset" runat="server" />.
In the Code Behind I have the following code:
protected void Page_Load(object sender, EventArgs e)
{
_service = new ArticleDataService(PortalId);
if (!IsPostBack)
{
string rawId = Request[ArticleQueryParams.ArticleId];
DisplayArticleDetails(rawId);
}
if (hdnNewAsset.Value.Trim() != string.Empty)
ProcessNewAsset();
}
Now, in my frontend, I have a javascript function to react to an event and set the hidden field and trigger a postback:
function assetSelected(assetGuid) {
$('input[id*="hdnNewAsset"]').val(assetGuid);
__doPostBack()
}
What's happening is that my hidden field is being set in the markup (chrome shows [
<input type=​"hidden" name=​"dnn$ctr466$Main$ctl00$hdnNewAsset" id=​"dnn_ctr466_Main_ctl00_hdnNewAsset" value=​"98d88e72-088c-40a4-9022-565a53dc33c4">​
] for $('input[id*="hdnNewAsset"]')).
However, when the postback occurs, hdnNewAsset.Value is an empty string.
What's even more puzzling is that at the beginning of Page_Load Request.Params["dnn$ctr466$Main$ctl00$hdnNewAsset"] shows 98d88e72-088c-40a4-9022-565a53dc33c4, and after the postback my hidden field has the same value (so the hidden field is persisting across postbacks), yet I cannot access this value via hdnNewAsset.Value.
Can anyone see what I"m doing wrong?
Ok I figured out the the issue.
The issue is that the code posted above was part of an ASCX user control. That user control was being loaded dynamically into an asp.net placeholder during the Page_Load event of the parent control.
Therefore, it seems that since both of these calls were in Page_Load of their respective calls, the inner control did not have it's values bound in the inner control's page_load. Modifying it so my inner control is loaded in Page_Init instead of Page_Load fixed all bindings.
Not sure if I wrote that in a way that makes sense to the general public.
Edit: It seems this part of the MSDN documentation is relevant to my issue:
If controls are created dynamically at run time or declaratively within templates of data-bound controls, their events are initially not synchronized with those of other controls on the page. For example, for a control that is added at run time, the Init and Load events might occur much later in the page life cycle than the same events for controls created declaratively. Therefore, from the time that they are instantiated, dynamically added controls and controls in templates raise their events one after the other until they have caught up to the event during which it was added to the Controls collection.

How to refresh webpage after clicking on “Update” in Grid view

I am working on an Asp.net, C# Application.
I want to Refresh the webpage after I clicking on “Update” LinkButton; in Grid view. I have tried the following code; however it just refreshes the page without saving the updated data in Grid view.
protected void LinkButton1_Click1(object sender, EventArgs e)
{
Response.Redirect(Request.RawUrl.ToString());
}
Name of DataSource SqlDataSourcePlan
SELECT [PlanID], [Deposit], [DepositReturn], [Discount] FROM [PaymentPlan] WHERE ([Ref] = #Ref)
UPDATE [PaymentPlan] SET [Deposit] = #Deposit, [DepositReturn] = #DepositReturn, [Discount] = #Discount WHERE [PlanID] = #original_PlanID
Use RawUrl instead:
Response.Redirect(Request.RawUrl)
The raw URL is defined as the part of the URL following the domain
information. In the URL string
http://www.contoso.com/articles/recent.aspx, the raw URL is
/articles/recent.aspx. The raw URL includes the query string, if
present.
Edit: "without saving the updated data in Grid view"
Why do you think that redirecting the page to itself should save something somewhere?
Have a look at this tutorial: Inserting, Updating, and Deleting Data with the SqlDataSource (C#)
I assume that you actually want to update the GridView instead of the whole page. Then you should call GridView.DataBind().
My guess (without some other informations in the code it is difficult to say) is that althought the information is saved in the database, the datasource for the gridview is not refreshed with the new values.
I have seen this problem often regarding this part.
You have to rebind the gridview with Page.DataBind or GridViewName.DataBind() (where GridViewName is the name of your gridview) before the redirect.
You probably don't reload the GridView at PageLoad or PageLoad does not occure (can't know without the server code). If that would work properly, you would not need the databinding before redirecting.

Categories

Resources