what is keyword If Page.IsPostBack how can use it - asp.net

What is this keyword how can use it?
If Page.IsPostBack = False Then

IsPostBack
Here is an overview of IsPostBack from MSDN:
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
It quotes:
true if the page is being loaded in
response to a client postback;
otherwise, false.
The postback is useful, say for example you have a Literal control on the page, and the code on page load sets the Literal.text += "hello"; If you have a button on that page, and press it, the text of the literal will get longer and longer, hellohellowhello, if you wrap the code in (c# example):
if(!Page.IsPostBack){
Literal.text += "hello";
}
The Literal text now wont expand when the button is pressed.
Other Notes
Instead of:
If(Page.IsPostBack = False)
Do:
If(!Page.IsPostBack)
This is logically the same and is generally accepted to be a better way of writing the statement.
Also you marked the question C#, but the If syntax you used indicates you are writing it in VB.net, not C#.

Gets a value indicating whether the page is being loaded in response to a client postback, or if it is being loaded and accessed for the first time.
Return Values:
true if the page is being loaded in response to a client postback; otherwise, false.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx

The IsPostBack tells you whether or not the page has been Posted Back, meaning "server side" button has been clicked.
You can "use" it by reading its value and acting upon it.
It's useful for example when you add controls dynamically to your page, so you don't have to add them when it's a PostBack.
Official documentation already been posted by others, look there for any further or technical details.

Related

SP2010 - httpcontext.response.write() not working for LinkButton's onClick event

probably a simple oversight I've missed (though I vaguely recall some obscure blogpost about the inner workings of Response.Write not working as expected in some situations but I don't remember if this is one of them):
The situation is, I have a Link Button on a control running in SP2010, and if I don't use HttpContext.Response.Write(), everything works as expected (ie I can change the .Text value for a Label). However, if I call Context.Response.Write(), while I can debug and step through the code, nothing seems to happen any more (nothing is written back and changes to other controls do not appear). It's being run on an application page in _layouts, appearing in a modal dialog.
(basically, I'm trying to do this - http://acveer.wordpress.com/2011/01/25/using-the-sharepoint-2010-modal-dialog/ but it doesn't work. EDIT: If I change it to a asp:Button, it still doesn't work)
Here's some code if you're interested:
.aspx:
# Page Language="C#" AutoEventWireup="true" ...
<asp:LinkButton CssClass="button remove" runat="server" OnClick="remove_Click" Text="Remove" ID="remove"></asp:LinkButton>
.aspx.cs:
public void remove_Click(object sender, EventArgs e)
{
....
//if successful
HttpContext context = HttpContext.Current;
if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
{
testControl.Text = "test code";
//doesn't work, and prevents line above from working
Context.Response.Write("<script type='text/javascript'>alert('hi!');</script>");
Context.Response.Flush();
Context.Response.End();
// context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");
// context.Response.Flush();
// context.Response.End();
}
}
Anyone come across something similar?
EDIT: some more interesting pieces that may help,
The button itself lies within an UpdatePanel
I do have a AsyncPostbackTrigger assigned
Using Response.Write from Web Forms code behind is problematic at best. As a rule of the thumb: never ever use Response.Write from a Web Forms page or user control.
The reason Response.Write is problematic, is because it is not part of the page's control tree, and rendering infrastructure. This means that when used within events in it will output the text outside of the normal page flow, and usually outside of the proper HTML page structure.
This is also why things go awry when you're using them in combination with UpdatePanels. As UpdatePanels are specifically designed to replace parts from a page, the infrastructure needs to know which parts. A Response.Write happens completely outside of this, and there's no real way of knowing where to render it. At best, the ScriptManager will perform a Response.Clear to wipe out your Response.Writes, at worst you'll break the UpdatePanel protocol body and you'll get a JavaScript error.
To top things off, any literal <script> tag will be ignored when you're performing a partial page update, as the browser's innerHTML feature used to fill in the HTML fragments sent by the server does not execute <script> tags.
Now, with all this theory out of the way -- is there no way to execute a piece of JavaScript code through an UpdatePanel? It turns out there is, and it's a lot cleaner than just executing a Response.Write: ScriptManager.RegisterClientScriptBlock and ScriptManager.RegisterStartupScript. For example:
ScriptManager.RegisterClientScriptBlock(
theButton, // control or UpdatePanel that will be rendered
typeof(YourPage), "UniqueKey", // makes your script uniquely identifiable
"alert('Testing!');", true);
The important part is the first argument: now the ScriptManager will know when to execute your script. If you register it on a control that is not updated on a partial page refresh, your script will not execute. But if the UpdatePanel containing the control is refreshed, your script that is hooked up to it will also execute. And that's usually exactly what you want.
If you always want to execute your script, regardless of which panel updates, you'd call
ScriptManager.RegisterClientScriptBlock(Page, ... );
#Ruben provided a very good answer, but I felt I could add useful content that doesn't fit in a comment.
There are a few occasions in SharePoint where you use a Response.Write - namely when dealing with webparts that are displayed within a SharePoint Modal popup and you want to do something cute with the callback when using window.frameElement.commitPopup().
The fact that you are using Response.Write within an update panel is actually part of your issue. When a postback that was generated with an update panel returns, the response is formatted with UpdatePanelId|Response Content where UpdatePanelId is the div associated with the update panel and Response Content is the new inner HTML of the div. When you use response.write, that format is lost, therefore the ScriptManager has no idea what to do with the response and should ignore it as erroneous. #Ruben provided you a method of registering scripts within an UpdatePanel.
Context.Response... should have a lower case context
ie:
context.Response.Flush()
etc
or am I missing the point?

Asp.Net CultureInfo switching: trying to avoid non postback calls

As if in this article I implemented an easy way to switch between languages on a website.
The issue is if I want to switch languages with a dropdown list, and leave the last selected language on the dropdown list control's view.
Every article I've seen about CulturalInfo-switching sends a Server.transfer() call right after the language switch, and that event causes the non-postback page reloading, including my dropdownlist control which realoads from default position.
I tried a response.redirect(), but it still is a non postback call
I think I need a way to check if it's a Server.transfer() call in the page load, but still haven't found a way to develop this
Thank you.
Assuming you followed the same approach as in that article, how about this:
string path = this.Request.Path;
if (path.LastIndexOf('?') > 0)
path += "&lang=" + senderLink.CommandArgument;
else
path += "?lang=" + senderLink.CommandArgument;
this.Server.Transfer(path);
Then, on the page that this.Server.Transfer executes, get lang value from this.Request.QueryString["lang"], and set the dropdown's SelectedItem appropriately.
Alternatively, keep Server.Transfer(Request.Path);, but on the receiving page, parse Session["MyCulture"] instead to set the dropdown. +1

Move Focus to Server Side Validator

I have a page with multiple CustomValidators and I want the focus to be brought to the offending validator when there is an error. I know this is possible with client side validation, but is it possible with server side?
Additionally, the CustomValidators are located in different parts of the page so I can't simply scroll the page to one general location when there is any validation failure.
I have tried:
SetFocusOnError
CustomValidator.Focus() immediately after validation, after the button click, and in Page.PreRender()
Thanks in advance
Thanks to a colleague, I have a solution to this question. It's so simple I wish I had come up with it! Just inject javascript when the validator fails and that javascript will be executed on postback.
Private Sub CustomValidator_ServerValidate(ByVal source as Object, ByVal args as System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator.ServerValidate
If someCondition Then
args.IsValid = True
Else
args.IsValid = False
System.Web.UI.ScriptManager.RegisterStartupScript(Me, Me.GetType(), "JumpToValidator", "jumpToValidator(validatorId);", True)
End If
End Sub`
where jumpToValidator(validatorId) is a javascript function that scrolls to the element passed in as an argument.

asp.net imagebutton firing on Enter key

I researched this problem here on SO and tried the apparent solution which did not work, so here it is:
I have a very complex form with among other controls, three autocompleting textboxes.
I also have a client who cannot seem to stop entering a value in the textboxes and hitting the Enter key to select the desired value from the autocomplete list.
When they hit Enter, the first imagebutton in the form fires, doing something completely different. So to them, the form is broken.
What I need to do is to prevent the Enter key from firing these imagebuttons (there are 10 of them in the form).
I have tried the following code in both Page_Load and Page_LoadComplete, neither of which work:
imgbtn1.Attributes.Add("onkeydown", "return (event.keyCode!=13);")
Any advice that saves me a few hairs is appreciated.
One good solution can be found here:
Disable Button click, ImageButton click and/or form submit on Enter Keypress
Adding Markup from Link
<form id="form1" runat="server">
<input type="submit" style="position:absolute;left:-100px;top:-100px;width:0px;height:0px;" onclick="javascript:return false;" />
<!-- other form controls below this line -->
</form>
Did you check these two references
http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
http://www.webcheatsheet.com/javascript/disable_enter_key.php
They are essentially doing the same thing you are trying, just that they are hooking it up to a different event. Also make sure that your Javascript is foolproof i.e. if javascript has some errors, then your end result may not be as expected.
The second link Subhash Dike posted (Disable Enter Key) worked for me. I have two ImageButtons and they both don't fire a postback when using this function (bit modified from the original) which is great.
document.onkeypress = function (evt) {
return ((evt) ? evt : ((event) ? event : null)).keyCode != 13;
};
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.Page.Form.DefaultButton = BtSearch.UniqueID
If Not IsPostBack Then
' ...............
End If
End Sub
I had a similar problem.
Listview1.ImageButton was responding to ENTER.
We really want a SAVE to happen (or nothing, but the bad behaviour was reloading the page and that made them grumpy)
Set up a handler for the window to catch events. I do this in docReady()
function docReady() {
$(document).keydown(mapKeyCode);
};
In that handler, find the keycode you want to capture ( enter is 13)
https://css-tricks.com/snippets/javascript/javascript-keycodes/
function mapKeyCode(event) {
{
if (event.keyCode == 13) {
//event.stopPropagation();
//event.preventDefault();
__doPostBack('ctl00$cp1$InventoryPieces$btnSubmit', '');
}
}
event.StopPropogation will cause nothing to happen.The keystroke is simply eaten. That may be what you want. You are still free to call an ajax method below, that's not part of the event.
event.PreventDefault is supposed to stop the event from doing what it normally does. I had troubles seeing a difference w/ this line commented out or not. There is in depth discussion on preventDefault and ENTER here on SO.
This 3rd line is what the people who pay me want to have happen when they hit the ENTER key even though they probably should be hitting tab. I tried (#).trigger() and didn't have a lot of luck. Inspecting the element, I saw that it was calling __postback, so I pasted that in. I'm reasonably certain ().Trigger would work if i figured out what i was doing wrong, I just took another route.
This is hackish to me, but it accomplishes the objective.
Hope it helps.

page.isvalid vs this.isvalid

Is there any difference between using This.IsValid vs Page.IsValid?
Page IsValid shows you if whole page is valid
this.IsValid returns information if object and each controls on it is valid.
'this' could be for example user control, so result could be different.
If this.IsValid is false then Page.IsValid is also false, but if this.IsValid is true then you are not sure that Page.IsValid is also true.
It depends on the context. In your webpage's code-behind file, in your webpage's event functions, this is getting your actual webpage instance (which inherits Page), and calls it's .IsValid method.
Page.IsValid() would be the same as this.Page.IsValid(). In this case, Page is getting a reference to the page that the calling control resides in (this), which would be the same instance as what I described above. So, in this sense, there's no difference.

Resources