ASP.Net WebForm: How IsPostBack property gets true when form submit - webforms

see this code
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
}
}
i just like to know who and how IsPostBack property gets true when form submit just clicking on submit button. who set the IsPostBack property to true ?
please share the info if anyone knows it.

It's a property controlled by the ASP.NET framework in the System.Web dll - specifically in the System.Web.UI.Page class.
/// <summary>Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.</summary>
/// <returns>true if the page is being loaded in response to a client postback; otherwise, false.</returns>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPostBack
{
get
{
if (this._requestValueCollection == null)
{
return false;
}
if (this._isCrossPagePostBack)
{
return true;
}
if (this._pageFlags[8])
{
return false;
}
if (this.ViewStateMacValidationErrorWasSuppressed)
{
return false;
}
if (this.Context.ServerExecuteDepth > 0 && (this.Context.Handler == null || base.GetType() != this.Context.Handler.GetType()))
{
return false;
}
return !this._fPageLayoutChanged;
}
}

Related

Razor Page filter to detect a session timeout and intercept Ajax calls

I looked at several posts and never could quite hit upon a .NET Core 3.1 Razor Page solution for my issue of a user clicking an Ajax enabled button on a page and having the application appear to process but actually does nothing since the session has timed out. I'm looking for them to be redirected to another page.
Here's what I have from several of posts - doesn't work, clearly the wrong approach. Your suggestions would be greatly appreciated.
public class PageFilterAjaxTimeOut : IPageFilter
{
public void OnPageHandlerExecuted(PageHandlerExecutedContext context)
{
if (context.HttpContext.Items["AjaxPermissionDenied"] is bool)
{
context.HttpContext.Response.StatusCode = 401;
}
}
public void OnPageHandlerExecuting(PageHandlerExecutingContext context)
{
}
public void OnPageHandlerSelected(PageHandlerSelectedContext context)
{
bool isAjax = context.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
if (!context.HttpContext.User.Identity.IsAuthenticated || context.HttpContext.Session.GetString("User") == null)
{
if (isAjax)
{
//HttpContext clear content;
context.HttpContext.Response.ContentLength = 0;
context.HttpContext.Items["AjaxPermissionDenied"] = true;
}
else
{
context.HttpContext.Response.Redirect("~/Errors/401");
}
}
}
}
<script>
$(document).ajaxError
(function (xhr, props)
{
if (props.status === 401) {
window.location.href = "#Url.Page("/Errors/401")";
}
}
);
</script>

Windows Form Multi-Select for Tree View

Is there a way to multi-select in a Windows Tree View? Similar to the image below
I know that .NET currently doesn't have a multiselect treeview. It is treated as a wrapper around the win32 native treeview control. I would like to avoid the Treeview's Checkbox property if possible. Any suggestions is greatly appreciated!
Im gonna assume you're trying to avoid check boxes. Here is an example:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
treeView1.DrawMode = OwnerDrawText;
treeView1.DrawNode += treeView1_DrawNode;
treeView1.NodeMouseClick += treeView1_NodeMouseClick;
}
private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e) {
// Show checked nodes with an underline
using (SolidBrush br = new SolidBrush(e.Node.TreeView.BackColor))
e.Graphics.FillRectangle(br, e.Node.Bounds);
Font nodeFont = e.Node.NodeFont;
if (nodeFont == null) nodeFont = e.Node.TreeView.Font;
if (e.Node.Checked) nodeFont = new Font(nodeFont, FontStyle.Underline);
using (SolidBrush br = new SolidBrush(e.Node.TreeView.ForeColor))
e.Graphics.DrawString(e.Node.Text, nodeFont, br, e.Bounds);
if (e.Node.Checked) nodeFont.Dispose();
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
if (Control.ModifierKeys == Keys.Shift && e.Node.Parent != null) {
// Extend selection
bool check = false;
foreach (TreeNode node in e.Node.Parent.Nodes) {
if (node.Checked) check = true;
node.Checked = check;
if (node == e.Node) break;
}
}
else {
unselectNodes(treeView1.Nodes);
e.Node.Checked = true;
}
}
This question has been answered here but I'll briefly answer your question. While it is true that Native Treeview control does not allow multiple selection, you can derive a subclass from it and override its behaviors.
Example code:
checkNodes method:
private void checkNodes(TreeNode node, bool check)
{
foreach (TreeNode child in node.Nodes)
{
if (child.Checked == true)
{
MessageBox.Show(child.Text);
}
//MessageBox.Show(child.Text);
checkNodes(child, check);
}
}
Treeview method after check:
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Action != TreeViewAction.Unknown)
{
if (busy) return;
busy = true;
try
{
TreeNode _node = e.Node;
checkNodes(e.Node, e.Node.Checked);
if (e.Node.Checked)
{
MessageBox.Show(e.Node.Text);
}
}
finally
{
busy = false;
}
}
}
It is not trivial to do so, however it can be done.

GWT - setText and setValue not working for TextBox on initial load

I have a couple of text-boxes on a page where the user can enter some numeric values; however, try as I might, I can't fill those text-boxes with default values - specifically I would like 0.0 displayed in both upon page load.
Here is how I create them and what I have tried -
GroupSection engineering_group = new GroupSection();
KSTextBox engrDesignTextBox = new KSTextBox();
engrDesignTextBox.setWidth("2.875em");
//engrDesignTextBox.setWatermarkText("0.0"); ==> this works, but not what I need
//engrDesignTextBox.setText("0.0"); ==> this doesn't work
engrDesignTextBox.setValue("0.0"); // doesn't work either
KSTextBox engrScienceTextBox = new KSTextBox();
engrScienceTextBox.setWidth("2.875em");
//engrScienceTextBox.setWatermarkText("0.0"); ==> this works, but not what I need
//engrScienceTextBox.setText("0.0"); ==> this doesn't work
engrScienceTextBox.setValue("0.0"); // doesn't work either
I'm thinking that I need to attach an "onload" event listener and then try the setText in there? That seems overkill for something that should be rather simple.
Incidentally, I have attached onBlurHandlers for both these text boxes and they work as expected (see code below)
The following code will simply insert0.0 if the user clicks or tabs out of the text-box while it is EMPTY.
engrDesignTextBox.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent blurEvent) {
if(((KSTextBox)blurEvent.getSource()).getText().length() < 1) {
((KSTextBox)blurEvent.getSource()).setText("0.0");
}
}
});
engrScienceTextBox.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent blurEvent) {
if(((KSTextBox)blurEvent.getSource()).getText().length() < 1) {
((KSTextBox)blurEvent.getSource()).setText("0.0");
}
}
});
EDIT : As requested here is how I have defined the setText and setValue methods in KSTextBox
public class KSTextBox extends TextBox implements HasWatermark {
.
.
.
#Override
public void setText(String text) {
String oldValue = super.getText();
if(hasWatermark) {
if(text == null || (text != null && text.isEmpty())){
super.setText(watermarkText);
addStyleName("watermark-text");
watermarkShowing = true;
}
else{
super.setText(text);
removeStyleName("watermark-text");
watermarkShowing = false;
}
}
else{
super.setText(text);
}
ValueChangeEvent.fireIfNotEqual(this, oldValue, text);
}
#Override
public void setValue(String value) {
if(hasWatermark) {
if(value == null || (value != null && value.isEmpty())){
super.setValue(watermarkText);
addStyleName("watermark-text");
watermarkShowing = true;
}
else{
super.setValue(value);
removeStyleName("watermark-text");
watermarkShowing = false;
}
}
else{
super.setValue(value);
}
}
So, getting back to the original question, how I do I initially set the values for these textboxes to 0.0?
That should have worked.Its very suprising. Is there a possibility that some other code is resetting the value after you did a setText or a setValue? Try debugging it in hosted mode.Put a breakpoint in setText and see when and how many times it is getting invoked

Metro App OnNavigatedTo setting textbox value in a different method

I am following around on a kindle book I bought for developing metro apps. For some reason I cannot set the text value of a text box in a method outside the OnNavigatedTo method. This is the code that the book provides:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//passed in the view model
viewModel = e.Parameter as ViewModel;
this.DataContext = viewModel;
viewModel.PropertyChanged += (sender, eventArgs) =>
{
if (eventArgs.PropertyName == "SelectedItemIndex")
{
if (viewModel.SelectedIndex == -1)
{
SetItemDetail(null);
}
else
{
SetItemDetail(viewModel.GroceryList[viewModel.SelectedIndex]);
}
}
SetItemDetail(viewModel.GroceryList[viewModel.SelectedIndex]);
};
}
private void SetItemDetail(GroceryItem item)
{
ItemDetailName.Text = "test"; //(item == null) ? "" : item.Name;
ItemDetailQuantity.Text = "test"; //(item == null) ? "" : item.Quantity.ToString();
//if (item != null)
//{
// ItemDetailStore.SelectedItem = item.Store;
//}
//else
//{
// ItemDetailStore.SelectedIndex = -1;
//}
}
I have commented parts out in the set item detail method, but I still cannot set the value of a textbox when I click it (this is supposed to be the behavior). I have used break points and the property of the textbox is getting set, however, it is not displayed on screen.
Thanks.

ASP.NET DropDownList not set to the selected item in async call

I am using VS 2010 (framework 4.0) for website development along with rad/telerik controls. The scenario is I have radwindow popup, actually a confirmation message box. On the basis of decision I have to call the base page again where have to call respective function. Here I want to set Country dropdownlist and state dropdowlist. I call the server side event in javascript function on OnClientClose event of Radwindow and in server side function call respective functions to set the form fields where I set Country and State list as well. But when I try to set Country selected value, it not get selected though there are items in dropdownlist. Here is the code,
Javascript function
function OnradWndConfirmSelfOwnerClose(oWnd) {
var hdn = document.getElementById("<%= hdnIsOwner.ClientID %>");
try {
var arg = oWnd.argument;
if (arg == "YES") {
hdn.value = 'true';
}
else {
hdn.value = 'false';
}
__doPostBack('<%=this.btnInitializeOwnerForm.UniqueID %>', '');
}
catch (err) { }
}
Server side function,
protected void btnInitializeOwnerForm_Click(object sender, EventArgs e)
{
bool IsOwner = !String.IsNullOrEmpty(hdnIsOwner.Value) ? Convert.ToBoolean(hdnIsOwner.Value) : false;
if (IsOwner)
{
SaveOwner();
}
else
{
InitializeOwnerData();
}
}
and in InitializeOwnerData() there is call for SetDefaultFields() function,
private void SetDefaultFields(ApplicationAccessInfo objAAInfo)
{
//Set Company Information fields
txtOrganizationName.Text = objAAInfo.EntityorOrganization;
txtCompanyWebsite.Text = objAAInfo.CompanyWebsite;
txtStreetAddress.Text = objAAInfo.StreetAddrees;
txtOfficeNumber.Text = objAAInfo.SuiteorOfficeNumber;
txtCity.Text = objAAInfo.City;
if (Guid.Empty != objAAInfo.CompanyCountryId)
{
**ddlCountry.Items.FindByValue(objAAInfo.CompanyCountryId.ToString()).Selected = true;**
PopulateStateList();
if (ddlCountry.SelectedItem.Value != "0")
**ddlState.Items.FindByValue(objAAInfo.CompanyStateId.ToString()).Selected = true;**
}
txtPostalCode.Text = objAAInfo.PostalCode;
//Disable Company Information fields
txtCompanyWebsite.Enabled = false;
txtOrganizationName.Enabled = false;
txtStreetAddress.Enabled = false;
txtOfficeNumber.Enabled = false;
txtCity.Enabled = false;
txtPostalCode.Enabled = false;
ddlCountry.Enabled = false;
ddlState.Enabled = false;
}
Item not get selected at ddlCountry.Items.FindByValue(objAAInfo.CompanyCountryId.ToString()).Selected = true
so ultimately gets error on,
ddlState.Items.FindByValue(objAAInfo.CompanyStateId.ToString()).Selected = true;
Note that when I call this same function normally then all works perfectly. In this scenario I found Items in Country list and objAAInfo.CompanyCountryId is also in the list.
Please help me out of this

Resources