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….
SamCashAsked:
Who is Participating?
 
Duy PhamFreelance IT ConsultantCommented:
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?
In your current code, you set label text before Response.Redirect. It means that you set the label for current page load cycle. However Response.Redirect immediately stops the current page load cycle and redirects user to new page load cycle. And in new page load cycle, your label is not set, that's why you don't see the message.
Use the Cookie is okay, and remember to clear Cookie after you set label text. But I would recommend using Session instead, it gives us more control because Session is Server-side cache, and easy to use and cleanup. If users close browser, Session will just disappear, while Cookie won't.

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 ....
Note that form submit is different from btn_click in most cases, except that button is submit button of the form (requires no server OnClick event handler).
However the idea is more or less the same:
Create a ScriptMethod to validate your required variables (UID, LID, AID) and maybe return an error message as well. This method can be called using Ajax
On form submit (onsubmit) or on Ajax initializeRequest, store the current postback element or button click, then cancel the form submit/abort ajax request
Call your ScriptMethod to validate required variables using Ajax
If a required variable missing, display message. No postback will be done.
If required variables are valid, set a flag variable (javascript) to indicate that we already done validation, just proceed the postback. And then re-do the postback (stored in previous step). Remember to reset the flag variable for next time.
0
 
Duy PhamFreelance IT ConsultantCommented:
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

0
 
SamCashAuthor Commented:
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
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
Duy PhamFreelance IT ConsultantCommented:
@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).
0
 
SamCashAuthor Commented:
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
0
 
SamCashAuthor Commented:
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
0
 
Duy PhamFreelance IT ConsultantCommented:
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.
0
 
SamCashAuthor Commented:
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

0
 
SamCashAuthor Commented:
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
0
 
Duy PhamFreelance IT ConsultantCommented:
Glad that it helps :).

Best Regards,
Duy.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.