Checking Page.IsPostBack in user controls - c#

Is it recommended to check the Page.IsPostBack in a user control Page_Load Event like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
I am getting wierd results
Edit ~ Here is the thing. When the main form is loaded, I use Request.QueryString to get the customer id which I then place in a SESSION variable.
On the control Load event I read the SESSION variable to get the data for that customer. So, do I need to check PostBack at the control level?
Edit ~ Here is the load event of the control
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Getting and storing the customer account number
if (string.IsNullOrEmpty((string)Session["CustomerNumber"]))
{
Session["CustomerNumber"] = cust.GetCustomerNumber(myHelper.GetCustomerIDFromQueryString());
LoadProductData();
}
}
}
Here is the myHelper Class
static class myHelper
{
public static Guid GetCustomerIDFromQueryString()
{
//Getting the GUID (used as customerid in CRM) from the URL request of the selected account.
return Sql.ToGuid(System.Web.HttpContext.Current.Request["ID"]);
}
}
}

If you use "!IsPostBack" in page load, when the user click other control it do a postBack, so you don't get your data.
I hope that helps you.

Just checking it for no reason? Absolutely not. If you should do something only on first load and not on subsequent post backs then it's the pattern that should be used.

Are you sure that you will always have a "CustomerNumber" already stored in the Session by the time you get to your page? Is there any rhyme or reason that you can find as to when you get data and when you don't?

Related

Make a field read only based on value in ASP.net: C#, ASP.Net

Everyone that has responded to my questions have been so very helpful and I am closing in on finishing this app. My challenge now is to make 3 fields read only based on a login.
I have the following code that does exactly what I need and assign the currently logged in user to a text field. What I want to do is make some other text fields (Read Only) if the login user does not equal a specific value. For example, if submitted_by_email_username does not equal administrator1#samplecompany.com then make the text field (Salary_in) which is a textbox, Read Only. I can read code much than I write it these days so I apologize if this is a simple request. I would like to make three fields Read Only based on that logic in the COde Behind.
protected void Page_PreInit(object sender, EventArgs e)
{
if (submitted_by_email_username != null)
{
_ = Context.User.Identity.Name;
if (User.Identity.IsAuthenticated)
submitted_by_email_username.Text = User.Identity.Name;
}
}
First of all, you don't need code in Page_PreInit 99.9% of the time in webforms. Even with dynamic controls you would only need Page_Load.
But you can make a TextBox readonly by using the Enabled property.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
submitted_by_email_username.Enabled = false;
submitted_by_email_username.Text = User.Identity.Name;
}
}

Navigation Source in Windows Phone

I have 2 pages in my application, A and B.
If I'm navigation from the outside of the application to A, I want to display a message box. If I'm navigation from B to A, I don't want to display anything.
Is there any way to identify in A the page which initiated navigation? i.e in A.Loaded (or any other event) I need something like
if(pageFromWhichIAmComingFrom == B)
OnNavigatedTo, OnNavigationFrom and OnNavigatedFrom don't seem to help me.
You could use the PhoneApplicationService class to store information about what page you were on last. For example, use OnNavigatedFrom on Page A:
void OnNavigatedFrom(object sender, Eventargs e)
{
PhoneApplicationService.Current.State["LastPage"] = "PageA";
}
And then check for that on the next page:
void OnNavigatedTo(object sender, Eventargs e)
{
if(PhoneApplicationService.Current.State["LastPage"].ToString() == "PageA")
{
// came from page A
}
else
{
// came from a different page
}
}
Hope this helps!
UPDATE:
One more thing I just saw that might be worth trying is using the NavigationService.BackStack property. I haven't tried this, but it seems like it should work. In your OnNavigatedTo event handler, you should be able to get the last entry from the stack to see your last page. This would be simpler and wouldn't require you to set any properties manually. Example:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var lastPage = NavigationService.BackStack.FirstOrDefault();
}
Found here.

Preserving DropDownList settings

I have a webpage: Menu.aspx, where I have the following controls of relevance:
a DropDownList with some values
a button, which redirects me to a page called Edit.aspx.
In my Edit.aspx page, I have a cancel button, which redirects the user back to the Menu page with the following C# method
protected void btnCancel_click(object sender, EventArgs e)
{
Response.Redirect("Menu.aspx");
}
What I would like to do is when I redirect my user back to Menu.aspx, I preserve the value of the DropDownList that they selected.
Thanks in advance!
EDIT: Ideally, I want to achieve this without a QueryString (if Possible)
EDIT2: I was thinking of something invovling a viewstate or postback but I'm unfamiliar with those.
When you called Response.Redirect("Menu.aspx"); you were already making a new request which the previous page was not part. It's like calling the page anew.
You can put the value in session before coming to Edit.aspx or pass the value back through query string
Response.Redirect("Menu.aspx?dropdownvalue=123");
On Menu.aspx, you'll check if ?dropdownvalue=123 exist and you set selected item to that value
Isn't the most ellegant solution, but you can create a session variable containing the selected value.
For example:
dropDown_SelectedIndex(object sender, EventArgs e)
{
Session["SelectedItem"] = dropDown.SelectedValue;
}
When you do the redirect, on the page load of the Menu.aspx, after you populate the DropDown, check if this session variable exists, then select the item and remove it from the application.
void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//populate drop down here
if(Session["SelectedItem"] != null)
{
dropDown.SelectedValue = Session["SelectedItem"].ToString();
Session["SelectedItem"] = null;
}
}
}
Or you can pass it via query string, but this way you preserve you url

Button click event error

Having just added a new button in my web application, I get an error when clicking on it, and I'm wondering if this is related to misplaced code. I will describe what/where I did, briefly. Thanks very much.
In ascx file:
<asp:Button ID="btn_rezerv" runat="server" Text="Reserve film" OnClick="btn_rezerv_Click"/>
In the ascx.cs file:
namespace CinProj.UserControls
{
public partial class FilmsList : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateControls();
}
private void PopulateControls()
{
string categId = Request.QueryString["CategID"];
string filmId = Request.QueryString["FilmID"];
....
if (categId != null)
{
.....
}
if (filmId != null)
{
......
Button btn_rezerv = (Button)item.FindControl("btn_rezerv");
}
}
protected void btn_rezerv_Click(object sender, EventArgs e)
{
string fid = Request.QueryString["FilmID"];
ShoppingCartAccess.AddItem(fid);
}
}
}
"Server Error in '/' Application.
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. "
Another problem could be because your PopulateControls method should probably only be called when during the Page Load when it's not a PostBack. I can't tell from above, but to me it looks like it only needs done on Load. Try wrapping that call with this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateControls();
}
}
It's likely the result of making some sort of client change that the server doesn't know about. Many times this is the result of changing values in a dropdown in JavaScript, for example.
To fix, you could:
Do away with using JavaScript for said modification
Use an UpdatePanel and add your control to it. If the client needs to make a change, trigger the UpdatePanel's update in order for the control's viewstate to update.

using sessions variable

In my master page, I'm loading a variable in the session like this:
public partial class TheMasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewUserPreferences SessionUserPreferences = new ViewUserPreferences();
SessionUserPreferences = UserPreferences.GetUserPreferencesFromDB(6);
}
}
}
Then, in the code behind of a file, I have this:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var test = Session["SessionUserPreferences"];
}
}
But when I debug, test is null. What's causing the problem?
Also, if I put a break point in the master page, it doesn't trigger when I run the aspx page; is this normal?
Thanks.
First thing you are missing the assignment part for UserPreferences.GetUserPreferencesFromDB(6) to the Session object. (I read the comments for #Greg's answer and you mentioned that even after that it is not working.)
Second, Master Page's Page_Load Event is triggered after the Current Page's Page_Load Event, hence the value of Session["SessionUserPreferences"] is null in Current Page's Page Load event since it is not set yet.
Check this link for further information on Page Events:
http://msdn.microsoft.com/en-us/library/dct97kc3.aspx
You have to do Session["SessionUserPreferences"] = something; somewhere before you attempt to retrieve that. Are you setting it somewhere else that you didn't show?

Categories