Choose postback URL of according to situation - asp.net

I control if a user exist in database. If it dont exist, I want to stay login page. If it exist, I want to go Default.aspx page.
protected void BtnLogin_Click(object sender, EventArgs e)
{
if(condition is okey)
{
// go default.aspx
}
else
{
//stay this page
}
}
What can I write on comment lines to achive this?
Thanks!

Sounds like you just want to do a redirect:
protected void BtnLogin_Click(object sender, EventArgs e)
{
if(myCondition)
{
Response.Redirect("/default.aspx");
}
else
{
//stay this page
}
}
If you want to retain the POST data, you can use Server.Transfer instead (note: based on your edits, it doesn't sound like this is what you need - I think you just need Response.Redirect):
Server.Transfer("/default.aspx");
Note that transferring the handler of the POST like this will not cause a browser redirect and therefore will not change the browser URL.
If you need to actually POST to a different URL and have the browser update, you'll need to post directly to that URL using a cross-page postback (using the action attribute on the form element), validate on that page and then redirect back to the original page if validation fails.

Related

Wrong page after Login

If I click on a link(Without logging into the site) I am navigated to this page:
http://localhost:59196/Login.aspx?ReturnUrl=%2fTest%2fContacts.aspx
When I login to the site I want to be redirected to my Home page rather than Test Contacts.aspx page.
How can I resolve this?
If i do this then I'm not logged in.
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Login1_LoggingIn(object sender, LoginCancelEventArgs e)
{
Response.Redirect("Home");
}
Just change link url you clicking on to:
http://localhost:59196/Login.aspx?ReturnUrl=Index.aspx
I think you clicked on Test Contact.aspx page with out logging in and hence you have been redirected to the Login page with a query string as ReturnURl = test contact.aspx, which might be used to redirect from the login page.
So instead of using return url query string you can redirect directly to your page page from the log in button click in the login page.
Hope it works.
I mean in
Loginbutton_click()
{
//login validation code here
//after successful validation
Response.redirect("Yyourhomepageurlhere");
}
You want to redirect to
http://localhost:59196/Login.aspx?ReturnUrl=%2fTest%2fIndex.aspx
rather than
http://localhost:59196/Login.aspx?ReturnUrl=%2fTest%2fContacts.aspx
In other words the link that you click on should point to the first link above rather than the second.
The question that remains is how are the links generated? Are they hard coded or are you using MVC and generating the link somehow? Is the link even in your control to generate?
It would appear your code looks at the ReturnUrl query string parameter and on successful login redirects to it.
Did you come to the Login page from the Contacts page? If so then the ReturnUrl might have been generated dynamically depending on where you came from. You may require this to be fixed to being the Index page (I assume this is what you have called it). Be careful though, other developers may want to have this link be dynamic.
I must changed the event.
protected void Login1_LoggedIn(object sender, EventArgs e)
{
Response.Redirect("Home");
}

RequiredFieldValidator error_message appears after form is submitted

I submit form and the clear all the fields from code behind, and when page is re-rendered RequiredFieldValidator error message appears. I am submitting form and not using button's click event.
How can i avoid seeing validator message after form is posted back?
Thanks in advance.
You could add a Response.Redirect to a 'saved successfully' page rather than posting back to itself unless you need to stay on that page. But I will add a solution below if you want to remain on this page......
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
else
{
SaveRecordToDB();
Response.Redirect("/");
}
}
Assuming the submit page is the Default.aspx otherwise just redirect back to your own form page.

ASP.Net Page Not Posting Back - Reloading Instead

I have a simple ASP.Net login page. When the login button is clicked, the page should post back and the even should be handled by my server-side event handler. Instead, the page simply reloads. Page.IsPostBack is false.
I've put breakpoints in the Page_Load/Init (where applicable) handlers of the Master page, the ASPX page and the UserControl (ascx). When I hit the Login button, instead of getting a post back and having my event handler called, I simply get the page load as if it was a fresh request.
But that's not the end of it! The login page takes a single query string parameter: Login.aspx?id=123456. The above failure occurs when using this parameter. However, if I enable URL Rewriting in order to make the query Login/123456, the error does not occur; I get a post back and my event handler is called in this instance.
So why am I not getting the expected behaviour from my page? What about the rewritten URL is making the problem go away?
Login Button is declared in LoginUserControl.ascx:
<asp:Button ID="SubmitLinkButton" runat="server" Text='Log In' OnClick="SubmitLinkButton_Click"></asp:Button>
And the handler in the code behind:
protected void SubmitLinkButton_Click(object sender, EventArgs e)
{
Authenticate();
}
SubmitLinkButton_Click is never called. :(
Edit (more code):
//Page_Init on the Master page
protected void Page_Init(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
try
{
if (SessionFacade.User != null)
{
loginlabel.Text = "Logged in |";
LoginLink.Visible = true;
}
}
catch
{
FormsAuthentication.SignOut();
CacheFacade.RemoveSessionValues();
Session.Abandon();
Session.RemoveAll();
HttpContext.Current.Response.Redirect("~/Login.aspx");
}
}
else
{
loginlabel.Text = "";
LoginLink.Visible = false;
}
}
Page_Load on the ASPX page:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack.Equals(false))
{
/* Some business stuff that boils down to this: */
Session["company"] = Request["company"];
}
}
Page_Load on the Login Control:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//honestly, there's no code here
}
}
P.S: I need to keep the non-url-rewrite way of accessing the login page, because many users are still navigating to that URL.
P.P.S: Even if URL rewriting isn't enabled, the error still occurs.
Whenever I've seen this problem in the past it has usually been attributed to URL re-writing. I would usually reach for Fiddler to trace the HTTP activity. My hunch tells me after you click the button and see the POST request it will quickly be followed up by a 302 redirect to the login page.
You note that "The above failure occurs when using this parameter" of the login.aspx page. Are you certain there is no url-rewriter configuration that for example, may strip out any querystring values and do a redirect?
Try to check your caching policy. Possibly your request is cached
I cleared the history on my IE browser and the problem went away.
Did you try to use a different browser? Once I had a similar problem, and it solved by re-installing Firefox!

How to know that we come to a page after redirecting from another page

I'm using a single page for two different purposes. By default it has one behavior and on coming to same page after redirecting via a link button it has a different behavior, like changing master page, etc...
How can I detect this and change the behavior accordingly?
If you have one page with two different behaviours then I would suggest that you want something like a querystring parameter to differentiate between the two purposes (eg somepage.aspx?mode=changeMaster). You can then check for this value and change your behaviour accordingly.
If you are only every doing the second behaviour from one place then its probably easiest to let it have a default behaviour rather than requiring the mode parameter (so you wouldn't have to change all your links to the page, just that one linkbutton). This should be much more reliable than relying on referrers and other such things which aren't always sent.
Use HttpRequest.UrlReferrer Property
You can know the page where you come from with the referer field that comes in the header. In asp.net you can retrieve it like this:
string MyReferrer;
if(Request.UrReferrer != null)
{
MyReferrer = Request.UrlReferrer.ToString();
}
I don't know asp.net but I'm pretty shure you can get it from the HTTP-headers referer/referrer field.
http://en.wikipedia.org/wiki/HTTP_referrer
Assuming you have control over the pages that a user redirects to and from, set a Session variable when you perform an action that your page should base its behavior upon.
For instance, in a LinkButton_Click event, you could set a Session variable like so:
protected void LinkButton_Click(object sender, EventArgs e)
{
Session["Source"] = "MyLinkButton";
}
And in your page's Page_Load or Page_Init event, check the value of that Session variable and perform the page's change in behavior based on the value in that Session variable.
protected void Page_Init(object sender, EventArgs e)
{
if (Session["Source"] == "MyLinkButton")
{
// do something
}
else if (Session["Source"] == "SomethingElse")
{
// dome something else
}
}

Recursive redirect on error handler page

I use the following MSDN code on my master page to detect if the browser accepts cookies:
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack) {
if(Request.QueryString["CookieTest"] == null) {
Response.Cookies["TestCookie"].Value = "Test";
Response.Redirect("CookieCheck.aspx.redirect=" + Server.UrlEncode(Request.Url.ToString())));
}
else if((string)Request.QueryString["Test"] == "passed") {
// my stuff...
}
}
}
The CookieCheck.aspx contains the following:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.Cookies["TestCookie"] == null)
Response.Redirect(Request.QueryString["redirect"] + "?Test=notPassed", true);
else
Response.Redirect(Request.QueryString["redirect"] + "?Test=passed", true);
}
Within the web.config i have defined the following:
<customErrors mode="On" defaultRedirect="Error.aspx" />
Now the recognizing of the cookies works well, but I have this problem: Whenever an error occurs on the page and I should be redirected to Error.aspx (and this worked before the whole cookie detection thing), the redirection seems stuck in an infinite loop and appends more and more "?Test=passed" to the URL. I should mention that the Errors.aspx also has the same masterpage and thus also performs the cookie check. However I have no clue why the redirection doesn't stop. Is there a way to solve this problem other than to exlude the Errors.aspx page from having the master page? Thank you very much.
If the CookieCheck.aspx page also uses the same Master page it will keep redirecting recursively, make sure that CookieCheck.aspx is not using the same MasterPage.
I'd rather recommend not using MasterPages for this, Master Pages by design are for Visual Inheritance not code Inheritance, if you wish to make some special type of pages that checks for the the browser ability to use cookies, you can have a new base class for these pages
public abstract class CookieEnabledPage : Page
{
}
and add your logic to this class, then whenever you need to make a new page with this behavior you inherit from this base class. I think this is a much cleaner way of doing what you want.
I guess the masterpage (or the combination masterpage-error.aspx) is raising an exception which triggers a redirect to error.aspx, which in turn causes the masterpage to restart its lifecycle and raise a new exception. The concatenation of "?Test=passed" is almost certainly a side effect of reinvoking the cookie test every time an error redirect occurs.
I suggest firing up the debugger and setting a breakpoint at Page_Load in Masterpage.aspx.cs and step through until you are redirected to the error page (the last line which gets execued is the one raising the exception).

Resources