Why my submit button submit twice? - c#

HTML Page
<body>
<form id="form1" action="Default.aspx" method="post">
<input runat="server" id="txtuser" type="text" />
<input runat="server" id="txtpwd" type="password" />
<input type="submit" value="Login"/>
</form>
</body>
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Login();
}
}
private void Login()
{
if (checkUser(Request.Params["txtuser"],Request.Params["txtpwd"]))
{
Response.Redirect("Success.aspx");//if success
}
}
I am developing a web page for old mobile version (like nokia N70) facing a problem. When I submit my username and password then check user return true to redirect to a new page. But it won't redirect to success.aspx. So I debug point on the Response.Redirect code, it can stop there and I continue run become error because getting the username&password null. Then I realized it loaded the page twice. How to solve it?

You want to login when there IS a PostBack. Not the other way around.
Change
if (!Page.IsPostBack)
to
if (Page.IsPostBack)
Make sure you have set AutoEventWireup to true in Code Front:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"...
otherwise Page_Load is never fired.

You should use Forms Authentication in a proper way, like explained here
You should do something like this for your redirect:
if (checkUser(userName.Text, password.Text))
{
FormsAuthentication.RedirectFromLoginPage(userName.Text, false);
}

Related

Call aspx event handler with http request

Consider the following code from behind an aspx page:
protected void onBtnClick(object sender, EventArgs e)
{
}
Is it possible to create/craft a POST request (HTTPWebRequest/HttpClient) to call the event handler behind of the aspx page ?
Thanks
Out of curiosity I was able to get this to work, but it takes specific changes to your .aspx page that you probably do not want to do (or cant do): <%# Page EnableEventValidation="false" also have to set your ClientIDMode to static
Given this Test.aspx webform markup:
<form id="form1" runat="server">
<asp:Button runat="server" OnClick="OnClick" Text="Click Me" ClientIDMode="Static" ID="Button1" />
</form>
And this codebehind:
protected void OnClick(object sender, EventArgs e)
{
Response.Write("clicked");
}
I was able to post to Test.aspx from an arbitrary html page (same site) and have OnClick fire, also Page.IsPostBack was set to true:
<form method="post" action="Test.aspx">
<input type="hidden" name="Button1" value="Click+Me" />
<input type="hidden" name="__VIEWSTATEGENERATOR" value="" />
<input type="hidden" name="__VIEWSTATE" value="" />
<input type="submit" value="submit" />
</form>
Again, this is not recommended, probably opens Test.aspx up to all kinds of nasty hacks.

best practices for dynamic content

I have a pretty extensive Classic ASP background (using server-side javascript), and my company is finally (FINALLY) making the push towards recoding everything in ASP.Net (using C#). I have a good grasp on good programming practices in Classic ASP and I usually try to make sure I code things the "right" way. I've been reading ASP.Net tutorials and feel like I have a pretty understanding of the basics. I have good discipline about separating client side javascript into external js files, keeping styling outside of the markup in external css files, etc. So, when reading these novice tutorials I understand the concept of the code-behind pages. It makes sense to me to separate the c# code from what will ultimately become the markup for the page. Making < asp:button > objects and the code-behind rules to alter them makes perfect sense.
However, I'm having a hard time wrapping my head around how to do something simple like I would have done in Classic ASP like this:
<%
if (condition) {
%>
<input type="button" value="click me" onclick="dosomething()" />
<%
}
else {
%>
<span>You don't have permission to see the button</span>
<%
}
%>
I'm having a hard time trying to figure out how I'm supposed to fit the conditional stuff you see above into the code-behind page. If I was showing a button under both circumstances, I'd make an <asp:button> object and style it in the code-behind page accordingly - but in the example above I'm only showing the button if the condition is true, and a span block if false.
I know that you don't HAVE to put ALL the c# code in the code-behind page. I can use the <% %> tags the same way I would do in Classic ASP. But, if I do that then it seems to me that it lessens the relevance of the code-behind page. For example, I know you can use an external css stylesheet to stylize your page and at the same time use inline styles on individual tags as well. I believe this to be poor practice, however. It makes it difficult to later have to adjust the styles on that element if you don't know whether to look in the markup or in the css file to find the relevant styles affecting that element.
It seems to me that the same would hold true for your markup and code-behind pages. Is it just a necessary evil to have to mix the 2, or is there a better way to do what I'm demonstrating above?
You could have in your markup:
<asp:Button .. Visible="False" />
<asp:Label .. Text="You do not have permissions" Visible="False" />
Note the Visible property. ASP.NET web forms is build on the idea of an object model, so the button and label are objects you can work with. In the code behind, you can have:
protected void Page_Load(object sender, EventArgs e) {
.
.
if (Xcondition = true) {
Button1.visible= true;
Label2.Visible = false;
}
else {
Button1.visible= false;
Label2.Visible = true;
}
}
Is the traditional way to accomplish this. You just have to figure out where in the lifecycle you need to do this, as load may not be the best (Init or PreRender event, for instance). If you only need to do this at startup once, do if (!Page.IsPostBack) { .. } to ensure it only runs once.
I made a small example that you can basically just copy/paste and mess around with a little.
This is the aspx code:
< body>
<form id="form1" runat="server">
<div>
<asp:TextBox runat="server" ID="txtCondition"></asp:TextBox>
<asp:Button runat="server" Text="Check condition" ID="btnCheckCondition" OnClick="btnCheckCondition_Click" />
<asp:Button runat="server" Text="Click me" ID="btnSubmit" OnClick="btnSubmit_Click" Visible="false"/>
<asp:Label runat="server" ID="lblMsg"></asp:Label>
</div>
</form>
</body>
this is the code behind: (if you double click on the btnCheckCondition, the click_event method will be automatically generated in your codebehind.
protected void btnCheckCondition_Click(object sender, EventArgs e)
{
if (txtCondition.Text == "Show the button")
{
btnSubmit.Visible = true;
lblMsg.Text = "You are allowed to see the button.";
}
else
{
lblMsg.Text = "You are NOT allowed to see the button.";
}
}
This will basically check the input in the textbox txtCondition. If it is equal to "Show the button", the second button will become visible. If the text is something else, the button will not appear and a label will say that you are not allowed to see the button.
have a label and a button in the page. check the condition from code behind and based on the condition, hide or show the control. you can use visibility attribute of the controls to hide or show them. Also use asp.net controls so that you can access them from code behind.
Unless you have a good reason not to, use the Visible property. (In ASP.NET Web Forms, you're asking for trouble if you change the structure of the component tree dynamically other than using repeater controls.) What I do is:
Page.aspx
<button type='button' Visible='<%# condition %>' runat='server'>
Click Me!
</button>
<span Visible='<%# !condition %>' runat='server'>
No button for you!
</span>
Page.aspx.cs
protected void Page_Load() {
if (!IsPostBack) DataBind(); // evaluates <%# ... %> expressions
}
(My preference is to make controls to "pull" data from code-behind instead of pushing it there, and use anonymous and plain HTML controls over their heavier equivalents when possible.) Any way of setting Visible before the page renders will work though.
First to help you with the easy way, to been able the condition to been recognized you need to define it and make it public on code behind. For example:
<%if (condition) {%>
<input type="button" value="click me" onclick="dosomething()" />
<%}else { %>
<span>You don't have permission to see the button</span>
<% } %>
and on code behind
public partial class OnePage : System.Web.UI.Page
{
public bool condition = false;
protected void Page_Load(object sender, EventArgs e)
{
// here change the condition
}
}
Second case with function call
<%if (fCheckAuth()) {%>
<input type="button" value="click me" onclick="dosomething()" />
<%}else { %>
<span>You don't have permission to see the button</span>
<% } %>
and on code behind
public partial class OnePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public bool fCheckAuth()
{
// return your evaluate
return false;
}
}
More asp.net form style
Now, working with the new asp.net (compared with the classic asp) you can also do that (and similar to that).
<asp:Panel runat="server" ID="pnlShowA">
<input type="button" value="click me" onclick="dosomething()" />
</asp:Panel>
<asp:Panel runat="server" ID="pnlShowB">
<span>You don't have permission to see the button</span>
</asp:Panel>
Use one asp:Panel to warp your full content, and on code behind you open it and close it.
public partial class OnePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (condition)
{
pnlShowA.Visible = true;
pnlShowB.Visible = false;
}
else
{
pnlShowA.Visible = false;
pnlShowB.Visible = true;
}
}
}
While the question is not about using ASP.NET Web Forms versus ASP.Net MVC. I felt compelled to point out that it may be more beneficial going with ASP.NET MVC rather than ASP.NET Web Forms in your scenario.
I say this because Classic ASP and ASP.NET MVC inline style is similar. In most cases you could probably convert ASP (<% %>) to Razor(a different flavor of in-lining server-side code with HTML) with little modification to the underlining logic. I don't know about you but the less code I have to write the better. For example, your above code would convert to the following Razor syntax:
#if (condition) {
<input type="button" value="click me" onclick="dosomething()" />
}
else {
<span>You don't have permission to see the button</span>
}
To answer your question, I would disable the button on the server-side. Have a disabled on the client. In the case the button is disabled, enable the Label with the appropriate text.
//Code-behind
bool correctPermission = true;
submit.Enabled = correctPermission;
noPermissionMessage.Enabled = !correctPermission;
//Client Code
<asp:Button ID="submit" runat="server" Text="Click Me" />
<asp:Label ID="noPermissionMessage" runat="server" Text="You don't have permission to see the button" Enabled="false" />

Protect an ASPX page with a password

I am making a page that the user should enter his password again to open and when he navigate away and come back again he should re-enter the password. NO SESSIONS OR COOKIES, just a simple page you enter the password you view it.
How can I do this ?
you should use 2 pages, one to enter the password, and the other to show the page...
the password page, will have a form as POST that points to page2.aspx
example of protected.aspx:
<form action="page2.aspx" mehod="post">
Pasword: <input type="password" id="pwd" name="pwd" />
<input type="submit" value="Enter" />
</form>
and the Page_Load event on page2.aspx should be something like
if(Request["pwd"] == null || Request["pwd"] != "123") {
Response.Redirect("InvalidPassword.aspx");
}
Use two divs.
One which contains the main content and other containing a textbox and button.
<div id="MainDiv" runat="server" Visible="false">Main Content goes here. </div>
And the login div
<div id="LoginDiv" runat="server" Visible="true">
<asp:TextBox ID="PasswordTextBox" runat="server"></asp:TextBox>
<asp:Button ID="LoginButton" runat="server" Text="Button" OnClick="LoginButton_Click" /></div>
On login button click handler, check the password and toggle the visibility.
protected void LoginButton_Click(object sender, EventArgs e)
{
if(PasswordTextBox.Text=="Password")
{
MainDiv.Visible=true;
LoginDiv.Visible=false;
}
}

How to open page in new window/tab or in same window/tab depending on Login success?

I have Login page wich is IFrame. If user successfuly logs in i want to open new page with his personal content, and if not I want error message displayed inside same iFrame.
This is my code:
<form class="register-form" runat="server" id='form1' target="_blank">
<div class="input username">
<asp:TextBox ID="tbUsername" runat="server" type="text" value="Username"></asp:TextBox>
</div>
<div class="input password">
<asp:TextBox ID="tbPassword" runat="server" value="Password" type="text"></asp:TextBox>
</div>
<div class="submit">
<asp:Button runat="server" ID="btnSignIn" type="button" OnClick="btnSignIn_Click">
</asp:Button>
</div>
</form>
As you can see i initially set forms target attribute to "_blank", and plan to change it dynamically.
This is my onclick event in code behind:
protected void btnSignIn_Click(object sender, EventArgs e)
{
if (Membership.Providers["CmsMembershipProvider"].ValidateUser(tbUsername.Text, tbPassword.Text))
{
Session["Username"] = tbUsername.Text.ToString();
FormsAuthentication.SetAuthCookie(tbUsername.Text, true);
Response.Redirect("../Pages/MyProjects.aspx");
}
else {
btnSignIn.OnClientClick = "openInSameWindow()";
Msg.Text = "Login failed. Please check your user name and password and try again.";
}
}
and this is simple js function:
<script type="text/javascript">
function openInSameWindow() {
var myForm = document.getElementById('form1');
myForm.target = '_self';
}
</script>
Page always opens in new tab/window.
I figured out that form already opens in new page before i set target to "_self" from code behind.
What is the best solution for this problem?
Page always opens in new tab/window. I figured out that form already
opens in new page before i set target to "_self" from code behind.
You are right. The ASP.net code gets executed AFTER target="_blank" is used for form. So your setting of target="_self" is wrong.
One solution for the problem you have is to use POPUP window to show the "../Pages/MyProjects.aspx" page.
Otherwise, I would prefer it if you can show "../Pages/MyProjects.aspx" in same window outside IFRAME. Otherwise keep the user in iframe showing appropriate message.
For first approach you will have to open the popup when user submits the form i.e. form.onsubmit handler. And on successful login set the location of POPUP to "Pages/MyProjects.aspx" otherwise close the POPUP. Ofcourse don't set target="_blank"
For second approach also don't set target (i.e. it should be _self) and on successful login set location like following.
window.top.location = "Pages/MyProjects.aspx"
such that your earlier function becomes
function openInSameWindow() {
window.top.location = 'Pages/MyProjects.aspx';
}
when there are errors, they will be displayed in iframe only.

How to handle validation when JavaScript is disabled in ASP.NET

I'm using some of the typical ASP.NET's Validation Controls in my website. Now I'm trying to disable the JavaScript in my browser to test my application and of course the Validation Controls no longer works. I think it's best to try to make them work using one of the suggested solutions down here instead of reinvesting the wheel and build a validation layer for the page or my objects -Am I thinking right?-
What do you think of these options and why:
Include in clicked button's event a code to check if the page is valid and if not explicitly call the Page.Validate(); method
Check if whether the JavaScript is enabled and if not I should call Page.Validate();
If you there's a better way to do it please let me know.
Javascript form validation is purely for user convenience. This stops them from submitting a form with an invalid phone number or whatever.
All inputs should actually be validated on the server when whatever request is being made is received. Here's the ideal flow, and you'll see that a browser not having javascript enabled is no big deal:
browser -> javascript validation (optional) -> server validation (if this fails, go back to initial page with errors)
So even if they have no JS, the page still submits the data, then you can return an error from the server. This is a poorer user experience typically (full page reload, potential retyping of inputs unless you repopulate the forms) which is why JS is often included in validation schemes.
The validation controls are designed to validate primarily on the server side. The client-side validation is optional (see the EnableClientScript property). So if they aren't working with Javascript disabled, then you're probably missing a little boilerplate code in your page, such as this snippet from the MSDN documentation on Page.IsValid:
private void ValidateBtn_Click(Object Sender, EventArgs E)
{
Page.Validate();
if (Page.IsValid == true) // yes, it is written this way in the MSDN documentation
lblOutput.Text = "Page is Valid!";
else
lblOutput.Text = "Some required fields are empty.";
}
You can also call Page.Validate and check Page.IsValid in your Page's OnLoad event, so that you can prevent a postback from proceeding to the next step when the form needs to be re-submitted. You probably don't even need to call Validate() explicitly — Button.CausesValidation is true by default.
You will need to do custom Server Side validation... http://msdn.microsoft.com/en-us/library/aa479013.aspx (information toward the bottom)
Something like this:
<%# Page Language="C#" %>
<script runat="server">
void Button1_Click(Object sender, EventArgs e) {
if (Page.IsValid) {
Label1.Text = "VALID ENTRY!";
}
}
void ValidateNumber(object source, ServerValidateEventArgs args)
{
try
{
int num = int.Parse(args.Value);
args.IsValid = ((num%5) == 0);
}
catch(Exception ex)
{
args.IsValid = false;
}
}
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
Number:
<asp:TextBox id="TextBox1"
runat="server"></asp:TextBox>
<asp:CustomValidator id="CustomValidator1"
runat="server" ControlToValidate="TextBox1"
ErrorMessage="Number must be even"
OnServerValidate="ValidateNumber"></asp:CustomValidator>
</p>
<p>
<asp:Button id="Button1" onclick="Button1_Click"
runat="server" Text="Button"></asp:Button>
</p>
<p>
<asp:Label id="Label1" runat="server"></asp:Label>
</p>
</form>
</body>
</html>

Categories

Resources