Client-side JS and ASP.NET Postback - asp.net

I have some client-side JavaScript that sets form fields. When the page posts back, those fields are reset.
Why is this? Aren't the field values captured and put in the ViewState when the postback occurs?
EDIT: When I break the debugger on Page_Load(), before any code executes after the postback, the form field values are empty.

Are the form elements that are being populated from your client-side javascript set as disabled? If so, ASP.NET will ignore the value.
For example:
<asp:TextBox ID="TextBox1" Enabled="False" Runat="Server" />
<script type="text/javascript">
document.forms[0].elements["TextBox1"].style.disabled = false;
document.forms[0].elements["TextBox1"].value = "Value set from Javascript";
</script>
When this code runs, ASP.NET thinks that the textbox is disabled, and therefore discards its value in the postback, so the value of TextBox1.Text will always be blank. As far as I know, this behavior applies to all form elements. If ASP.NET thinks they are disabled, and they are subsquently enabled and populated client-side, the value won't be available on the postback.

Yes. It sounds like you have something else going wrong (perhaps an OnLoad handler that isn't checking the IsPostback field and therefore overwriting your changed values?).

Check what is being initialized on server side, the most common issue that I have seen is that any server side initialization code doesn't check for IsPackBack like so:
if (!Page.IsPostBack) {
// Do Work
}

The other thing to check is whether you are doing a postback or a callback. If you're doing a callback, the form field values sent back with the callback are the ones the page first sent to the client. For some reason ASP.NET AJAX pickles these values and sends them with every callback, instead of reading the form field afresh.

It's because I had enabled="false" set on the fields. I changed the fields to readonly="true" and the same thing happens.
The solution was to change the fields to readonly at runtime using JS.

Related

Detecting target of postback early in page_load to exit so click handler can run

I have a webforms page with a gridview and several other buttons. In debugging, I've noticed all the binding to gridview executes during postback in the Page_Load sub. Only after this is all done do the click handler(s) get invoked and in my case the handler does a Response.Redirect to another page.
So, I found this on SO: Run the button event handler before page_load.
It suggests the possibility of detecting the target of the postback during page_load and I was thinking of exiting the page_load in this case and letting the button click handler load a new page (i.e. avoiding all the wasted building and formatting of the gridview.
Here is a snippet from my Page_Load:
If IsPostBack Then
Dim targetOfPostBack As String = Request.Params("__EVENTTARGET").ToString()
End If
During PostBack the __EVENTTARGET is always an empty string rather than something suggesting the "add" button I clicked (i.e. ctl00$MainContentPlaceHolder$btnAddEvent). Trapped here:
The OP on SO above is expressing this same approach in C# while my implementation is VB.Net. What am I doing wrong?
On your asp button try setting UseSubmitBehavior="False"
Use the UseSubmitBehavior property to specify whether a Button control uses the client browser's submit mechanism or the ASP.NET postback mechanism. By default the value of this property is true, causing the Button control to use the browser's submit mechanism. If you specify false, the ASP.NET page framework adds client-side script to the page to post the form to the server.
When the UseSubmitBehavior property is false, control developers can use the GetPostBackEventReference method to return the client postback event for the Button. The string returned by the GetPostBackEventReference method contains the text of the client-side function call and can be inserted into a client-side event handler.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.usesubmitbehavior(v=vs.110).aspx
You can write a client side script to redirect the page thus avoiding the postback all together. Set "OnClientClick" (Asp.NET Button) or "OnClick" (HTML Buttom) property and then simply return false.
Eg:
Script:
function RedirectToURL()
try {
window.open("<Your URL Here>", "_self", "menubar=0,resizable=
} catch (e) {
}
return flase;
}
Button :
<input type="button" id="btnToggleConfig" onclick="RedirectToURL()" runat="server"
value="Click here to Goto Link" />
This is the ASP.NET page life cycle at work: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.85).aspx
A few options:
check out this post for _EVENTTARGET being empty:
__EVENTTARGET is empty on postback of button click
Handle the redirect on the client side (if possible)
Only fill the gridview only once on page_load (If Not IsPostback) if that's an option
If you're only worried about the gridview being recreated and eating up some 'processing power' or time, depending on size, users, etc, may not be a big issue, so could leave as-is.

I'm having trouble understanding page validation

Okay, so I have my asp.net page with all of my comparison and requiredfield validators. This leaves me with two concerns.
What additional validation do I need? Do I need anything in the code behind? I want them to be unable to hit the 'save' button until their textbox information is complete, and it seems to be doing this with just the validator controls, but I'm unsure if there are other steps I need to take.
If I have a requiredfield validator and I want to turn it off under special circumstances, where in the codebehind would I set it to true? Can I do it on the 'save' button click, before it prevents the button from functioning?
1.
You need as many validations as necessary, you can create many different validators.
You need server-side validation in the code behind. If a postback occurred then the form passed the validation, but there are some validation features which are unusable at client-side. For instance you register to a homepage and you have a form where the username is required and there is a regular expression validator too. These validators will run at client-side. But if the username has to be unique and you can only check that using a database then obviously this can't be checked at the client-side, therefore, the client-side will evaluate the page to be valid, a postback will occur and it's the job of the server-side to check whether the username is unique.
Note that you can create custom validators if you need to do anything exotic.
2.
Depending on your needs you can set the Enabled property of your validators whenever you need to do that. Read more about that here.
As per my knowledge,
We should include a check for "Page.IsValid" on the server side (code behind) whenever we are using the ASP.NET Validators. This would ensure a check at the server side even if the javascript is being disabled on the browser.
No, you can't do that on the save button click as the button click would not be hit until the validation passes.
Hope this Helps!!
1 if you want add validation server
protected void Button1_Click(object sender, EventArgs e) {
//Proceed only if the validation is successfull
if (!Page.IsValid) {
return;}
}
2 You can set CausesValidation="false" to button
The #1 question with Page.IsValid is ok.
The requiredfieldvalidator is a javascript validator, so you can't disable it from codebehind once it was enabled (unless it satisfies the condition and you can go through). But it's possible to disable it via javascript, check this code:
ValidatorEnable(workPhoneValidator, false);
Link: Dynamically enable or disable RequiredFieldValidator based on value of DropDownList

Please help me understand AutoPostBack property of an ASP.NET control

I'm learning about ASP.NET, mainly by following through a book, but also making an effort to actually do things along the way. But, I came across an explanation about list controls which I don't understand. This is what it says:
"[in the context of the Smart Tasks panel]...the last option sets the AutoPostBack property of the control. With this option checked, the control will submit the page it's contained in back to the server as soon as the user chooses a new item from the list"
Can you explain this statement for me? Thanks in advance for your help.
For normal client controls (such as a list control with AutoPostBack set to false), when a user chooses an item in the list, the browser does not communicate with the server. There's no network traffic and no delay for your user before they see the results of the choice, but there's also no opportunity to do anything in your server code, like calculate dependent values. If you want to do anything to the screen in response to the choice, you have to use a client-side script.
When AutoPostBack is set to true, selecting an item in the list sends a message to the server (via an HTTP POST). ASP.NET then executes whatever code you have attached to the list's changed event, rebuilds the page, and sends the revised page to the client.
If you set AutoPostBack="true" on a control, when it's value changes, it will automatically postback to the server.
For example if you wanted a dropdown that when changed displayed different data in a table below or something, you might want to postback get the new value so your page could refresh the data.
This is opposed to style of the dropdown and a button beside it you click to postback, so instead of change value, click the button, you can just change the value with AutoPostBack="true".
A ListBox has a SelectedIndexChanged event that you can handle to detect when the selected item in a ListBox has changed. You'd configure it like this:
<asp:ListBox ID="ListBox1" runat="server" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"/>
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// Do something
}
With AutoPostBack="false" (the default), that event handler doesn't actually happen on the server in "real time". The user has to perform an unrelated action to submit (POST) the form, such as clicking a button, to make that event fire on the server.
If you want to take "real time" action on that event, you set AutoPostBack="true" which makes the form automatically submit every time the selected item is changed.
The benefit - you get "real time" notification of events. The drawback - the page talks a lot more to the server, so each click costs bandwidth and causes client "lag".
Further reading: http://www.dotnetspider.com/resources/189-AutoPostBack-What-How-works.aspx
When a user selects a ListItem (or whatever the collection item is), the page should automatically submit the web form to the server with a POST event.
here's the wikipedia page on HTTP POST events
http://en.wikipedia.org/wiki/HTTP_POST
The responsibility of an asp.net control contained in a Page is to render a part of the html that the user will end up seeing in his browser. Some controls support the AutoPostBack property. What it does is that it makes the control emit some extra javascript that will submit the form whenever the value of that control is changed, so that you can react to this on the server side.
Basically AutoPostBack is used so that whenever there is some change in the controls text or anyother change in the controls property, the page is submitted to the server.
Posting the page means, the page is submitted to the server. Suppose i use a textbox and i make its AutoPostBack = "true", now i write some text into it and click outside the textbox, then the page will refresh.
This refresh indicates that your value which you entered into the textbox has been submitted to the server.
The postback is handled by ASP.NET server. AutoPostBack will automatically post back your page to the server.
Add an event Handler. This will give you a better picture.
In your case of DropDownList: Add an eventhandler: double click the DropDownList, it will route you to an eventhandler:
Write something in that event handler let us say : Response.Write("message");
The page will refresh and you will see your message, this means the page was posted to the server and the server has executed your event handler and displayed you the message.
I hope this was usefull

purpose for <pages enableEventValidation="false">

I've used the following in web.config
<pages enableEventValidation="false">
This corrects a problem we've been having with Ajax.
We have a web page that if you browse to directly using a standard HTML hyperlink works fine.
If you browse to the page from another page via link inside a gridview and response.redirecting in the RowCommand event to the page passing an ID in the querystring. The page throws errors from controls inside the panel stating
"Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. "
I'm happy to leave the page validation as false as it seems to have had no other effect.
Any ideas what's happening?
Read the documentation.
EDIT: For security reasons, it's probably best to leave it set to true wherever you can.
I would therefore recommend that you set it to false only on the individual AJAX pages where it causes problems, while leaving it true in web.config.
From here
Invalid PostBack or CallBack argument error is basically raise because of Event Validation feature. The EventValidation feature is a new feature in ASP.NET 2.0, and provides an additional level of checks to verify that a postback from a control on the client is really from that control and not from someone malicious using something like a cross-site script injection to try and manipulate things. It is part of our overall strategy of increasingly adding security in depth levels to the programming model -- so that developers can be secure by default even if they forget to add security checks of their own.
Now, Invalid PostBack or CallBack argument error may occur when you are firing click event and the object is rebinding or its properties are changed in Page_Load event or someone is trying to hack into your system with cross site scripting. Each time .Net Framework render a page then it associate a unique Guid for all the controls. When binding a gridview or repeater, on each databind framework will associate a new guid for the contorl. So every time when you are firing event make sure Page_Load event does not change the control, because if the control changed the it will have a different Guid which have acutally fired the event for postback. Here are some scenario with this error.
1) Invalid Postback or Callback argument in GridView Problem may be: You are binding data in Page_Load event with either Object Data Source or Manual Binding with function call. This will make your GridView bind data on every event fire of any control. When you are firing any GridView command with OnRowCommand, before RowCommand fire your GridView will rebind and all control within it will be assigned to new id. So RowCommand could not get the item which have fired the event. Solution for Invalid Postback or Callback argument in GridView: You can bind your data within this if condition
if (!IsPostBack)
{
//Your code for Bind data
}
This code will definitely give you solution if this not work then check whether any other control is not giving error.
There is one thing worth adding here: If you want to disable the event validation for a specific control, rather than the entire page, there is a workaround documented here and here (and now referenced in the relevant Connect suggestion):
Simply subclass the relevant WebControl class, and don't set the SupportsEventValidation attribute on the subclass. The subclass will be exempt from event validation.

When should EnableViewState be enabled on a server control?

Is there any guideline or rule for when the view state should be enabled on a server control? And when it should not?
I was looking at this SqlDatasource example and noticed that the view state for the label control is not enabled:
<asp:Label ID="ErrorMessageLabel" EnableViewState="false" runat="server" />
Why isn't EnableViewState enabled on the label control? I know that enabling the view state carries some overhead so I would like to use it only when it is needed.
Here's a good rule of thumb: If you (1) change a property's value in the code-behind, and (2) need to know what value you set in a later postback without recalculating the value, then you need to use ViewState.
For example. In my page's markup I might have a Label control specified like this:
<asp:Label ID="TitleLabel" runat="server" Text="Update this Employee" />
Then in the Page_Load event I have this code:
If Not IsPostBack AndAlso myEmployeeObject.IsNew Then TitleLabel.Text = "Create a new Employee"
By changing the value of the Text property, I've introduced a new element into ViewState. If I get the value of the Label's Text property during any subsequent PostBack, the value will be "Create a new Employee".
Here's what I do when I set out to minimize the amount of ViewState used by my page. I enable tracing on the page. The trace output is added to the bottom of your page when its rendered in the browser. The trace output identifies every single server control on your page and includes how much ViewState (measured in bytes, I believe) each control stores. I use this information to calculate when I want to trade the overhead of ViewState for the overhead of recalculating values.
In my previous example, I would elect to recalculate the Label's Text property on every PostBack and stop storing the Text property in ViewState. This is how my updated markup would look:
<asp:Label ID="TitleLabel" runat="server" Text="Update this Employee" EnableViewState="false" />
And my updated Page_Load event:
If myEmployeeObject.IsNew Then TitleLabel.Text = "Create a new Employee"
Only time you should use viewstate is when you need to get the value of that sucker back on a postback or something. So for the label example you'd only need viewstate enabled if you had code that said something like
void Button1_Click()
{
label1.text += " more!";
}
without viewstate the postback couldn't figure out the contents of the label and you'd just get " more!" over and over with no append. try it.
Really, our the rule of thumb at my office is just turn it off at the page level and then enable it as you need it.
First understand the view state, here is a blog entry that might help.
Start developing your pages by disabling the viewstate at the page level. Most controls in asp .net 2.0 save state required for their functioning in the Control State thus disabling view state would not affect most controls.
For controls that do save data bound to them in the view state like List box, you can avoid the data from landing in the view state (which works fine for most use cases) by doing your binding on the PreInit event.
Other than that, if you don't have a third party control that needs it or so, the performance penalty you encur from using the view state far outweighs the promised preservation of state you get between postbacks.
And finally use tools that help you see the bytes going on in your page's view state. The ASP.NET View State helper and an add in into Fiddler which shows viewstate data would help you a lot in this respect.
only enableviewstate when you want to preserve the values across http requests, other than that keep it = false. also you dont have to enableviewstate to use a control.
Whenever you have a control on which the contents will be important (like a text box or drop list) you want to enable viewstate so that the content will available and update to date on a postback.
Anytype of control which outputs somewhat static text (stuff you are not getting back from the user) typically will not have viewstate enable. This minimizes the viewstate.
You need to make sure you understand the ViewState better. No blanket statement like "only enable the ViewState if you have to" will really make sense unless you do. Understand when the viewstate gets loaded/saved/dirtied.
here's one of the better articles i've seen
To be honest I can't think of any time you would want viewstate set to true for label controls. Its a quick way to make your w3wp.exe take up hoards of memory.

Resources