Link to home
Start Free TrialLog in
Avatar of SamCash
SamCashFlag for United States of America

asked on

Return from post back abort

on “page load post back”, some variables are initialized (UID), if there is a failure initializing these variables the code that is executed by the btn_click event will fail.  How can I return from page load without running the btn_click procedure?  
Abbreviated…
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
          }
          else
            {
                  UID = (string)(Session["UserContactID"]);
                  if (UID == null)
                   {
                          lblInStatus.Text = "Must have a valid UID";
                          return; //Early return without executing the btn_Click <<<<<<<<<<<<<<<<<<<<<<<<<
                    }
                    else //Continue normally….
Avatar of Duy Pham
Duy Pham
Flag of Viet Nam image

Why don't you check that required parameter in btn_Click procedure, such as
protected void btn_Click(object sender, EventArgs e)
{
    if (Session["UserContactID"] == null)
    {
        lblInStatus.Text = "Must have a valid UID";
    }
    else
    {
        // do what btn_Click shoud normally do here
    }
}

Open in new window

Avatar of SamCash

ASKER

Duy,

Thanks for the response.  Good question.  When we simplify the problem we loose some of the requirements.  There are about 100 or so btn, onselect, onTextChange... where this code needs to go (the variables control the data the user sees and is able to manipulate).  There will be at least 100 or so more in the near future.  However there are only 9 webpages where this goes.  Also there is some standard code that is at the top of each page where this will be included.  It would be easy for someone to miss adding it to an event, but it is not possible to miss the included code on page load, because the system will not work without it.

I am new to asp.net, there must be a way to return from page load.  I saw one suggestion, throwing an exception, but that seems pretty hacky.  I am still digging, I am beginning to understand the sequence of a post back.  I should ultimately find out how, but I am getting a lot of pressure from the boss, time wise...

Kind Regards
Sam
@SamCash:  You might be able to achieve that by using Response.Redirect on Page_Load. For example:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // check for error here
        if (Session["missingUID"] != null)
        {
            lblInStatus.Text = Session["missingUID"].ToString();
            Session["missingUID"] = null;
        }
        // do other stuffs as you need to
    }
    else
    {
        UID = (string)(Session["UserContactID"]);
        if (UID == null)
        {
            Session["missingUID"] = "Must have a valid UID";
            Response.Redirect(Request.Url.AbsoluteUri, true);
        }
        else // continue normally
        {
            // do what you need to do on PostBack here
        }
    }
}

Open in new window


However, in my opinion, the way your page have 100 and more controls doing whole Page PostBack isn't a good way. And trying to do late check on Page_Load is also not good. I would prefer do validate for missing UserContactID before actually doing the postback at client side (e.g.: by checking before form submits or before ajax request starts).
Avatar of SamCash

ASKER

Duy,

Great, that provides the functionallity requried.  Now for best practices, understanding I am inexperianced.

There are 3 required variables,

UID, (user id from session key)
LID, (league id from url, which is validated with the UID by a database call, ...WHERE UID = @UID AND LID = @LID.)
AID, (association id also from url, which is validated with the above LID by database call.

So if all 3 are valid, certain tabs and buttons are visible, and certain drop down lists are populated with the relative data for this user, league and association.

Using, the tabs(panels) and panels within the pages, we are only loading the necessary new data.  The point of this architecture is a valid user can only see and modify information based on his permissions, league and association.  So we are simply limiting (hiding) the controls and only populating the visible controls with the limited data.

So, best practices...  You mention "late check" I thought page load was the earliest opportunity for me to catch a non-authorized LID or AID if I have to verify via a db?  Is there a short cut to catch this before submitting?

ps, after Response.Redirect(Request.Url.AbsoluteUri, true); is there any clean up required as the (for example) btnBtn_Click is still 'queued, on a stack or somewhere' waiting for execution next, I think?

Looking forward to your further direction, thanks again.

Kind Regards
Sam
Avatar of SamCash

ASKER

Duy,

The label on the webpage does not update...
                    .
                    .
                   if (UID == null)
                   {
                    lblStatusMessage.Text = "Test Redirect";
                    Response.Redirect(Request.Url.AbsoluteUri, true);

I am using a label instead of a session variable, is that the issue?

Regards
Sam
When you specify the 2nd parameter of Response.Redirect = true, then current page is completely stopped for loading and all queued action (e.g.: btn_Click) will be ingored. So no need to do extra clean up, unless you have some user-defined data must be changed upon the required UID.

I am using a label instead of a session variable, is that the issue?
Yes, it's because you use label. The reason is that, when you set the label text, it is for current page load. But the page load will quickly be stopped and redirected to (the same page) new load cycle, meaning all the page will be rendered again.

So, best practices...  You mention "late check" I thought page load was the earliest opportunity for me to catch a non-authorized LID or AID if I have to verify via a db?  Is there a short cut to catch this before submitting?
If you are using ajax to postpack and update page data, you can check this AJAX request life cycle. Or if all your controls are in a form, you can do the check for the form with something like
<form ... onsubmit="return isRequiredUIDsValid();">
...
</form>

Open in new window

But either way, you need to write down required UID/LID/AID to hidden fields or create a Web Method with EnableSession = true. Also, it depends on how your UID/LID/AID are created/constructed to find out the best choice of early checking those required UID/LID/AID.
Avatar of SamCash

ASKER

Duy,

Thanks again for sharing your experience.  

Yes, it's because you use label.

If I use session cookies to hold the values and then assign the label to the cookie, the label will render the updated Status Message or re-render the old page?

<form ... onsubmit="return isRequiredUIDsValid();">

I can use ajax, I am familiar with updating panels.  All controls are in a form.

I am not seeing how ajax will help, my inexperiance...

%%%%%%%%%%%%%%%%%%%
The technique <form ... onsubmit="return isRequiredUIDsValid();>

Do I understand correctly?

When a btn_click occurs I can validate the 3 variables in the code behind,
if !valid, update status message, abort btn_click, return with updated status message
else update status message, continue btn_click event ....

%%%%%%%%%%%%%%%%%%%%%

Here is my code, I thought it may help me express my objective and the challenges.  The second shows example use of UID and LID to populate dropdownlist from the database.

Thanks again, I appreciate your assistance.
Sam

namespace WebApplication1.Debug
{
    public partial class Facility : System.Web.UI.Page
    {
        string RequestingPage = "Lucid: " + HttpContext.Current.Request.PhysicalApplicationPath + HttpContext.Current.Request.CurrentExecutionFilePath; //New2015_0423_1033!
        string UID, AID, LID, StatusMessage;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
#if DEBUG //set defaults for development - DEBUG
                //Test weather Brian or Tony's box... System.Environment.MachineName;
                string HostName = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
                if (HostName == "LENOVO-TONY")
                {
                    UID = "190";
                    AID = "193";
                    LID = "196";
                }
                else //assume "Brian"
                {
                    UID = "1";
                    AID = "2";
                    LID = "3";
                }
#endif
#if !DEBUG //RELEASE
                ddlUID.Visible = false;
                ddlLeagueID.Visible = false;
                //get UID, AID, LID from session, url, and database
                UID = "190";// (string)(Session["UserContactID"]); // from session set to "190" to pretest Relase build
                
                // AID = ~not used on this page

                string appPath = Request.ApplicationPath;
                string LeagueURL = "bravesleague"; // appPath.Substring(appPath.LastIndexOf('/') + 1); set to "bravesleague" to pretest Release build;
                if (LeagueURL != null && LeagueURL != "")
                {
                    LID = Convert.ToString(BLogic.LeagueIDByUrlGet(LeagueURL, RequestingPage));
            }
#endif
                if (UID == null
                    || UID == ""
                    || LID == null // if root then qualify AID instead of LID
                    || LID == "")
                {
                    StatusMessage = BLogic.StatusMessageUpDate("Must have a valid UID and LID", StatusMessage); //appends this message to top of status log
                    lblStatusMessage.Text = StatusMessage;

                    UID = "0"; // setting these to "0" prevents sql exceptions during PopulatePage();
                    AID = "0";
                    LID = "0";
                }
                PopulatePage();
            }
            else //This is a POSTBACK
            {
                //Get Page Variables on postback
#if DEBUG
                if(ddlUID.SelectedValue != null){UID = ddlUID.SelectedValue;}
                AID = "2";
                if (ddlLeagueID.SelectedValue != null) {LID = ddlLeagueID.SelectedValue; }
#endif
#if !DEBUG
                //get UID, AID, LID from session, url, and database
                UID = "190"; // (string)(Session["UserContactID"]); // from session set UID = "190" to pretest Release build

                string appPath = Request.ApplicationPath;
                string LeagueURL = "bravesleague"; // appPath.Substring(appPath.LastIndexOf('/') + 1); set LeagueURL = "bravesleague" to pretest Release build;
                if (LeagueURL != null && LeagueURL != "")
                {
                    LID = Convert.ToString(BLogic.LeagueIDByUrlGet(LeagueURL, RequestingPage)); //Get LID from database
                }
#endif
                if (UID == null
                    || UID == ""
                    || LID == null // if root then qualify AID instead of LID
                    || LID == "")
                {
                    StatusMessage = BLogic.StatusMessageUpDate("Must have a valid UID and LID 2", StatusMessage);
                    lblStatusMessage.Text = StatusMessage;
                    Response.Redirect(Request.Url.AbsoluteUri, true);
                    //return; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& this does not work!
                }
            }
        }

Open in new window


 protected void PopulatePage()
{
            ddlSelectSchedule.DataSource = BLogic.GridNameTypeByLIDTypeGet(LID, UID, RequestingPage);
            ddlSelectSchedule.DataValueField = "ID";
            ddlSelectSchedule.DataTextField = "GridName";
            ddlSelectSchedule.DataBind();
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Duy Pham
Duy Pham
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of SamCash

ASKER

Duy,

Thanks again.  I have studied cookies and session cookies.  Your suggestion to use session["name"] works better than expected, it maintains my log across multiple pages throughout the session.

Kind Regards
Sam
Glad that it helps :).

Best Regards,
Duy.