Currently I have a website with a simple signup form in html, this is the code:
<div class="grid_6 push_3 block alpha">
<div class="grid_6 form_block alpha omega">
<label>שם משתמש</label>
</div>
<div class="grid_6 form_block alpha omega">
<input type="text" id="username" name="username" pattern="^\S{4,}$" required />
</div>
<div class="grid_6 alpha omega form_block">
<label>סיסמא</label>
</div>
<div class="grid_6 form_block alpha omega">
<input type="password" id="password" name="password" pattern="^\S{6,}$" required title="סיסמא צריכה להכיל לפחות 6 תווים" />
</div>
<div class="grid_6 alpha omega form_block">
<label>וודא סיסמא</label>
</div>
<div class="grid_6 form_block alpha omega">
<input type="password" id="password2" pattern="^\S{6,}$" required />
</div>
<div class="grid_6 alpha omega form_block">
<label>כתובת אימייל</label>
</div>
<div class="grid_6 form_block alpha omega">
<input id="email" name="email" type="email" required pattern="[^#]+#[^#]+\.[a-zA-Z]{2,6}" />
</div>
<div class="grid_6 alpha omega form_block">
<label>וודא כתובת אימייל</label>
</div>
<div class="grid_6 form_block alpha omega">
<input type="email" id="email2" required pattern="[^#]+#[^#]+\.[a-zA-Z]{2,6}" />
</div>
<div class="grid_6 form_block alpha omega">
<input name="submit" type="submit" onclick="return validateForm()" value="שלח" />
</div>
</div>
(Its actually being wrapped in tags from the master page, this is the master:
<%# Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="css/reset.css" rel="stylesheet" />
<link href="css/text.css" rel="stylesheet" />
<link href="css/963_9_10_10.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body dir="rtl">
<form runat="server">
<div class="container_9">
<div class="header grid_9">
<h1>סיכומים.נט</h1>
</div>
<!-- END HEADER -->
<nav>
<ul class="clearfix grid_6 push_3">
<li class="grid_1 alpha literature">ספרות</li>
<li class="grid_1 language">לשון</li>
<li class="grid_1 civics">אזרחות</li>
<li class="grid_1 history">היסטוריה</li>
<li class="grid_1 bible">תנך</li>
<li class="grid_1 omega english">אנגלית</li>
</ul>
</nav>
<div class="grid_3 pull_6" id="search">
<input type="text" id="search_box" placeholder="הקלד מילות חיפוש"/>
<input type="submit" value="חפש" id="search_button"/>
</div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<footer class="grid_9">
2013 © כל הזכויות שמורות לסיכומים.נט
</footer>
</div>
<!-- END CONTAINER -->
</form>
</body>
</html>
I also have a signup.aspx.cs file that inserts the signup information into the database as follows:
public partial class signup : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["submit"] != null) {
register1();
}
}
public void register1()
{
string sql = "INSERT INTO [userinfo] ([username], [password], [email]) VALUES (N'" + Request.Form["username"] + "', N'" + Request.Form["password"] + "', N'" + Request.Form["email"] + "')";
Database.UpdateData(sql);
}
}
I think i'm doing everything right so far (I'm a beginner in anything beyond html/css) but correct me if I've made any errors.
What I want to do now is validate my form input server-side before I insert it into my database. I want to check that it obeys all my rules, char-lengths, matching fields and so forth - and also that the username/email isn't taken already.
I'm currently doing some basic javascript validation but I understand that isn't sufficient security wise.
an explanation (as simple as possible) as to what I have to go about doing now, would be great. Ideally i would like to return to the signup page and list the errors at the top of the form in a customizable way.
thanks
The RegularExpressionValidator and CompareValidator are going to be your friends here.
For example:
<asp:RegularExpressionValidator id="valEmail" ControlToValidate="email"
ValidationExpression="[^#]+#[^#]+\.[a-zA-Z]{2,6}"
EnableClientScript="false" ErrorMessage="The email is invalid!"
runat="server" />
And:
<asp:CompareValidator id="valEmails"
ControlToValidate="email" ControlToCompare="email2" Type="String"
EnableClientScript="false" Text="The email addresses must match!"
runat="server" />
Optionally, you can wrap them all neatly in a ValidationSummary control.
Finally, check Page.IsValid in your codebehind.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["submit"] != null && Page.IsValid)
{
register1();
}
}
You can read about the other validation controls here.
Finally, fix your SQL so it's not vulnerable to SQL Injection:
string sql = "INSERT INTO [userinfo] ([username], [password], [email]) VALUES (N'" + Request.Form["username"].Replace("'","''") + "', N'" + Request.Form["password"].Replace("'","''") + "', N'" + Request.Form["email"].Replace("'","''") + "')";
You may want to use Asp.net server validation controls and Validation Summary Control
By using this control you can be sure that all rules will be followed. You can check it server side by using
if(page.IsValid)
{
//Code goes here
}
Related
Help!
I have a login and and a signup html form, each toggle on clicking respective links on the form itself and there is no postback or page refresh event.
the problem is asp.net does not allow me to have two runat=server forms.
i can access input fields of the forms.
i have added asp:Button in place of input type="submit" in the forms in order to acces onclick methods, but then again asp.net does not allow me to add asp button (server side control) when i remove runat="server" from any of the forms which is having this asp button!
The question:
How can i access submit button of the forms so that i can perform necessary code behind operations for signup and login
Is there a way to achieve my goal? (may be some way to hide one of the forms in starting and show it when i click toggle link )
Here's the login register form's
Code:
<div>
<header>
</header>
<section>
<div id="container_demo" >
<a class="hiddenanchor" id="toregister"></a>
<a class="hiddenanchor" id="tologin"></a>
<div id="wrapper">
<div id="login" class="animate form">
<form id="form1" action="#" runat="server" >
<h1>Log in</h1>
<p>
<label for="username" class="uname" data-icon="u" > Your email </label>
<input id="username" name="username" runat="server" required="required" type="text" placeholder="myusername or mymail#mail.com"/>
</p>
<p>
<label for="password" class="youpasswd" data-icon="p"> Your password </label>
<input id="password" name="password" runat="server" required="required" type="password" placeholder="eg. X8df!90EO" />
</p>
<p class="keeplogin">
<input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping" />
<label for="loginkeeping">Keep me logged in</label>
</p>
<p class="login button">
<asp:Button Text="Submit" runat="server" OnClick="Submit" />
<!--<input type="submit" value="Login" />-->
</p>
<p class="change_link">
Not a member yet ?
Join us //toggle link
</p>
</form>
</div>
<div id="register" class="animate form">
<form id="form2" action="#" runat="server" >
<h1> Sign up </h1>
<p style="margin-top:4px;margin-bottom:2px;">
<label for="usernamesignup" class="uname" data-icon="u">Your username</label>
<input id="usernamesignup" name="usernamesignup" runat="server" required="required" type="text" placeholder="mysuperusername690" />
</p>
<p style="margin-top:4px;margin-bottom:2px;">
<label for="emailsignup" class="youmail" data-icon="e" > Your email</label>
<input id="emailsignup" name="emailsignup" runat="server" required="required" type="email" placeholder="mysupermail#mail.com"/>
</p>
<p style="margin-top:4px;margin-bottom:2px;">
<label for="passwordsignup" class="youpasswd" data-icon="p">Your password </label>
<input id="passwordsignup" name="passwordsignup" runat="server" required="required" type="password" placeholder="eg. X8df!90EO"/>
</p>
<p style="margin-top:4px;margin-bottom:2px;">
<label for="mob1" class="uname" data-icon="u">Your mob no.</label>
<input id="mob" name="mob" runat="server" required="required" type="text" placeholder="9450.." />
</p>
<p class="signin button">
<asp:Button Text="Submit" runat="server" OnClick="Submitr" />
<!--<input type="submit" value="Sign up"/> -->
</p>
<p class="change_link">
Already a member ?
Go and log in //toggle link
</p>
</form>
</div>
</div>
</div>
</section>
</div>
Ok finally i got it after applying my brains!
this is what i did:
applied asp buttons on both server side forms
on signup form:
<asp:Button Text="tologin" runat="server" OnClick="changetologin" ForeColor="#1DA2C1" BackColor="#F7F8F1" />
on login form:
<asp:Button Text="Join us" runat="server" OnClick="changetosignup" ForeColor="#1DA2C1" BackColor="#F7F8F1" />
on page load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["form2"] == null && Session["form1"] == null) //show login hide signup
{
form1.Visible = true;
form2.Visible = false;
}
if (Session["form2"] != null && Session["form1"]==null ) //show signup hide login
{
form1.Visible = false;
form2.Visible = true;
Session["form2"] = null;
}
if (Session["form1"] != null && Session["form2"] == null) //show login hide signup
{
form1.Visible = true;
form2.Visible = false;
Session["form1"] = null;
}
}
on signup form on click of toggle button:
protected void changetologin(object sender, EventArgs e)
{
Session["form1"] = "clicked";
Response.Redirect("#tologin");
}
on login form on click of toggle button:
protected void changetosignup(object sender, EventArgs e)
{
Session["form2"] = "clicked";
Response.Redirect("#toregister");
}
In short:
combo of form visible property and session variable did the trick !!
Having a unusual problem with an application I'm building, so what I'm looking to do is a user can view preview of their adverts they have created, click the advert which is a dynamic link and be brought to a new page which will show the advert in more detail. The more detail page is then runs a to check the query string, pass the parameters of the query sting to a method which pulls the correct details form the database. This part works perfectly, but when the object is returned the pages loads again, calls the same method 3 times, but with null parameters which in returns a null reference to an object that doesn't exist.
I've tried to refactor the code so when a page loads it won't retrieve form the database unless the search parameters are valid. When the page loads, components won't work then, for example the Image Carousel.
I've tried hard coding the parameters into the method, will work perfectly. will only load once.
I've created two new pages which do not inherit form a master page and used the exact same methods. works perfectly. I tried the method on a two different pages that are inherited form the master page and same problem.
Detailed Page.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeFile="DetailAdvert.aspx.cs" Inherits="Lenders.ie.DetailAdvert" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="col-lg-9">
<div class="container">
<div class="row">
<!--Advert Image -->
<div class="container">
<div class="row">
<!-- Carosel goes here -->
<div class="row carousel-holder">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-10">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="item active">
<img class="slide-image" id="Img1" runat="server" src="http://placehold.it/800x380" alt=""/>
</div>
<div class="item">
<img class="slide-image" id="Img2" runat="server" src="http://placehold.it/800x380" alt=""/>
</div>
<div class="item">
<img class="slide-image" id="Img3" runat="server" src="http://placehold.it/800x380" alt=""/>
</div>
</div>
<a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
</div>
</div>
</div>
</div>
<!--User Details-->
<br />
<div class="container">
<div class="row">
<!-- Descriptin and profile view -->
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-5">
<div class="well well-sm">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<img src="" runat="server" id="imgProfilePic" alt="" class="img-rounded img-responsive" />
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<h4>
<asp:Label ID="lblFristName" runat="server" Text=""></asp:Label>
<asp:Label ID="lblSecondName" runat="server" Text=""></asp:Label>
</h4>
<small><cite title="Location"><asp:Label ID="lblLocation" runat="server" Text=""></asp:Label> <i class="glyphicon glyphicon-map-marker">
</i></cite></small>
<p>
<i title="Email" class="glyphicon glyphicon-envelope"></i> <asp:Label ID="lblEmail" runat="server" Text=""></asp:Label>
<br />
<i title="Join Date" class="glyphicon glyphicon-user"></i> <asp:Label ID="lblJoinDate" runat="server" Text=""></asp:Label><br />
<i title="User Rating" class="glyphicon glyphicon-stats"> </i><asp:Label ID="lblUserRating" runat="server" Text=""></asp:Label><br />
<i title="Contact Number" class="glyphicon glyphicon-phone"> </i><asp:Label ID="lblContactNumber" runat="server" Text=""></asp:Label>
</p>
<!-- Split button -->
<asp:Button ID="btnMessage" runat="server" Text="Message" CssClass="btn btn-success" />
</div>
</div>
</div>
</div>
<!-- Description / Product Details-->
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-5">
<div class="well well-sm">
<h4> Description: </h4>
<p>
<asp:Label ID="lblDesc" runat="server" Text=""></asp:Label>
</p>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<!-- Comment Section -->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-10">
<div class="well well-sm">
<h4>Comments</h4>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
</asp:Content>
Detailed Aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;
using DataModels;
namespace Lenders.ie
{
public partial class DetailAdvert : System.Web.UI.Page
{
public Advert_User ReturnedUserAdvet = new Advert_User();
public BalAdvertManger BALMan = new BalAdvertManger();
protected void Page_Load(object sender, EventArgs e)
{
//Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.ExpiresAbsolute = DateTime.Now.AddMonths(-1);
//GetData();
//PopulatePage();
//int UserID = Convert.ToInt32(Request.QueryString["UiD"]);
//int AdvertID = Convert.ToInt32(Request.QueryString["AdID"]);
if (!Page.IsPostBack)
{
GetData();
}
}
public void GetData()
{
//int UserID = 41;
//int AdvertID = 2;
int UserID = Convert.ToInt16(Request.QueryString["UiD"]);
int AdvertID = Convert.ToInt16(Request.QueryString["AdID"]);
if (UserID != 0 || AdvertID != 0)
{
ReturnedUserAdvet = BALMan.ReturnDetailedAdvert(UserID, AdvertID);
PopulatePage();
}
//int UserID = Convert.ToInt32(Request.QueryString["UiD"]);
//int AdvertID = Convert.ToInt32(Request.QueryString["AdID"]);
//int UserID = 41;
//int AdvertID = 2;
//ReturnedUserAdvet = BALMan.ReturnDetailedAdvert(UserID,AdvertID);
}
public void PopulatePage()
{
}
}
}
This is where the link is and directs to the Detailed page.
Profile Page.aspx
<%# Page Title="" Language="C#" EnableEventValidation="false" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="ProfilePage.aspx.cs" Inherits="Lenders.ie.ProfilePage1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<div class="container">
<div class="row">
<%-- Adverts View--%>
<asp:View ID="AdvertsView" runat="server">
<h2>Adverts</h2>
</asp:View>
<%-- View Adverts --%>
<asp:View ID="View_ViewAdverts" runat="server">
<h2>View Adverts</h2>
<div class="row">
<asp:Literal ID="Advert1" runat="server"></asp:Literal>
<asp:LinkButton ID="LinkButton1" OnClick="LinkButton1_Click" runat="server">LinkButton</asp:LinkButton>
</div>
</asp:View>
<%--There was three closing divs here--%>
<asp:View ID="MessageView" runat="server">
<h2>Messages</h2>
</asp:View>
</asp:MultiView>
</div>
</div>
</div>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
ProfilePage aspx.cs - Method that creates the link
public void DisplayUserAdverts()
{
int UserID = Convert.ToInt32(Session["UserID"]);
int i = 0;
ListOfUserAdverts = BalAdvertManager.ReturnUserAdvert(UserID);
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
foreach (Advert item in ListOfUserAdverts)
{
string ColDiv = "col-sm-4 col-lg-4 col-md-4";
string ThumbClass = "thumbnail";
string Image = "AdvertThumbnails/" + item.Img1.ToString();
string Caption = "caption";
string Link = "DetailAdvert.aspx/?AdID=" + item.AdvertID.ToString() + "&UiD=" + item.UserID.ToString();
Button btn = new Button();
writer.AddAttribute(HtmlTextWriterAttribute.Class, ColDiv);
writer.RenderBeginTag(HtmlTextWriterTag.Div);
writer.AddAttribute(HtmlTextWriterAttribute.Class, ThumbClass);
writer.RenderBeginTag(HtmlTextWriterTag.Div);
//writer.AddAttribute(HtmlTextWriterAttribute.Src, Image);
writer.AddAttribute(HtmlTextWriterAttribute.Href, Link);
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.AddAttribute(HtmlTextWriterAttribute.Src, Image);
writer.RenderBeginTag(HtmlTextWriterTag.Img);
writer.RenderEndTag();
writer.RenderEndTag();
writer.AddAttribute(HtmlTextWriterAttribute.Class, Caption);
writer.RenderBeginTag(HtmlTextWriterTag.Div);
//writer.AddAttribute(HtmlTextWriterAttribute.Src, Image);
//writer.RenderBeginTag(HtmlTextWriterTag.Div);
//writer.AddAttribute(HtmlTextWriterAttribute.Class, Caption);
writer.RenderBeginTag("h4");
writer.Write(item.Title.ToString());
writer.RenderEndTag();
writer.RenderBeginTag("p");
//Does Something
writer.Write(item.Desc.ToString().Substring(0, 50));
writer.Write("</br>");
writer.Write("Testing" + i.ToString());
writer.Write("</br>");
this.Controls.Add(btn);
writer.AddAttribute(HtmlTextWriterAttribute.Href, Link);
// writer.AddAttribute(HtmlTextWriterAttribute.Id);
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write("Link");
writer.RenderEndTag();
writer.RenderEndTag();
//writer.WriteBeginTag("p");
// // Does Something
//writer.WriteEndTag("p");
writer.RenderEndTag();
writer.RenderEndTag();
writer.RenderEndTag();
i++;
}
}
Advert1.Text = stringWriter.ToString();
}
Master Page.aspx
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs" Inherits="Lenders.ie.MasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Shop Homepage - Start Bootstrap Template</title>
<!-- Bootstrap Core Content -->
<link href="Content/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="Content/shop-homepage.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<form id="form1" runat="server">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<%-- <a class="navbar-brand" href="www.google.com">
</a>--%>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<asp:HyperLink ID="Home" runat="server">Home</asp:HyperLink>
</li>
<li>
<asp:HyperLink ID="Services" runat="server">Services</asp:HyperLink>
</li>
<li>
<asp:HyperLink ID="Contact" runat="server">Contact</asp:HyperLink>
</li>
<li>
<asp:HyperLink ID="Login" runat="server">Log In</asp:HyperLink>
</li>
</ul>
<div class="navbar-form navbar-right">
<div class="input-group input-sm">
<asp:TextBox ID="txtSearch" runat="server" CssClass="form-control form-control-sm " AutoPostBack="true"></asp:TextBox>
<span class="
</span>
</div>
</div>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<div class="container">
<div class="row">
<div class="col-md-3">
<p class="lead">Shop Name</p>
<div class="list-group">
<asp:HyperLink ID="HyperLink1" CssClass="list-group-item" runat="server">Sports</asp:HyperLink>
<asp:HyperLink ID="HyperLink2" CssClass="list-group-item" runat="server">Hobbies</asp:HyperLink>
<asp:HyperLink ID="HyperLink3" CssClass="list-group-item" runat="server">Life Style</asp:HyperLink>
<asp:HyperLink ID="HyperLink4" CssClass="list-group-item" runat="server">Another Example</asp:HyperLink>
<asp:HyperLink ID="HyperLink5" CssClass="list-group-item" runat="server"> Blah </asp:HyperLink>
</div>
</div>
<%-- <div class="col-md-9">
<div class="row carousel-holder">
<div class="col-md-12">--%>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder ID="ContentPlaceHolder2" runat="server">
</asp:ContentPlaceHolder>
</div>
</div>
<%-- </div>
</div>
</div>--%>
<div class="container">
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © Your Website 2014</p>
</div>
</div>
</footer>
</div>
<!-- /.container -->
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>enter code here
</form>
</body>
</html>
Master Page.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Lenders.ie
{
public partial class MasterPage : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
I have a simple button, that when clicked should display text in a label. However when I press the button, nothing happens. Any ideas where i could be going wrong?
Default.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default"%>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Button ID="testbutton" runat="server" Text="Button" OnClick="testbutton_Click" />
<asp:Label ID="testlabel" runat="server"></asp:Label>
</asp:Content>
Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void testbutton_Click(object sender, EventArgs e)
{
testlabel.Text = "You clicked the Testbutton";
}
}
Masterpage:
<%# Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>PhotoChunk</title>
<link href="css/bootstrap.css" rel='stylesheet' type='text/css' />
<link href="css/style.css" rel='stylesheet' type='text/css' />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800' rel='stylesheet' type='text/css'/>
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<script src="js/jquery.min.js"></script>
<!--<script src="js/jquery.easydropdown.js"></script>-->
<!--start slider -->
<link rel="stylesheet" href="css/fwslider.css" media="all" />
<script src="js/jquery-ui.min.js"></script>
<script src="js/fwslider.js"></script>
<!--end slider -->
<script type="text/javascript">
$(document).ready(function() {
$(".dropdown img.flag").addClass("flagvisibility");
$(".dropdown dt a").click(function() {
$(".dropdown dd ul").toggle();
});
$(".dropdown dd ul li a").click(function() {
var text = $(this).html();
$(".dropdown dt a span").html(text);
$(".dropdown dd ul").hide();
$("#result").html("Selected value is: " + getSelectedValue("sample"));
});
function getSelectedValue(id) {
return $("#" + id).find("dt a span.value").html();
}
$(document).bind('click', function(e) {
var $clicked = $(e.target);
if (! $clicked.parents().hasClass("dropdown"))
$(".dropdown dd ul").hide();
});
$("#flagSwitcher").click(function() {
$(".dropdown img.flag").toggleClass("flagvisibility");
});
});
</script>
<!----details-product-slider--->
<!-- Include the Etalage files -->
<link rel="stylesheet" href="css/etalage.css" />
<script src="js/jquery.etalage.min.js"></script>
<!-- Include the Etalage files -->
<script>
jQuery(document).ready(function($){
$('#etalage').etalage({
thumb_image_width: 600,
thumb_image_height: 400,
show_hint: true,
click_callback: function(image_anchor, instance_id){
alert('Callback example:\nYou clicked on an image with the anchor: "'+image_anchor+'"\n(in Etalage instance: "'+instance_id+'")');
}
});
// This is for the dropdown list example:
$('.dropdownlist').change(function(){
etalage_show( $(this).find('option:selected').attr('class') );
});
});
</script>
<!----//details-product-slider--->
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div class="header">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="header-left">
<div class="logo">
<img src="images/logowhite.png" alt=""/>
</div>
<div class="menu">
<a class="toggleMenu" href="#"><img src="images/nav.png" alt="" /></a>
<ul class="nav" id="nav">
<li>Browse</li>
<li>Upload</li>
<li>About</li>
</ul>
<script type="text/javascript" src="js/responsive-nav.js"></script>
</div>
<div class="clear"></div>
</div>
<div class="header_right">
<!-- start search-->
<div class="search-box">
<div id="sb-search" class="sb-search">
<form>
<input class="sb-search-input" placeholder="What are you looking for?" type="search" name="search" id="search">
<input class="sb-search-submit" type="submit" value="">
<span class="sb-icon-search"> </span>
</form>
</div>
</div>
<!----search-scripts---->
<script src="js/classie.js"></script>
<script src="js/uisearch.js"></script>
<script>
new UISearch(document.getElementById('sb-search'));
</script>
<!----//search-scripts---->
<ul class="icon1 sub-icon1 profile_img">
<li><a class="active-icon c1" href="#"> </a>
<ul class="sub-icon1 list">
<li class="list_img"><img src="images/1.jpg" alt=""/></li>
<li class="list_desc"><h4>Matthew Thompson</h4></li>
<li><div class="login_buttons">
<div class="check_button">Account</div>
<div class="login_button">Logout</div>
</div>
<div class="clear"></div>
</li>
</ul>
</li>
</ul>
<div class="clear"></div>
</div>
</div>
</div>
</div>
</div>
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
<div class="footer">
<div class="container">
<div class="row">
<div class="col-md-3">
<ul class="footer_box">
<h4>About PhotoChunk</h4>
<li>About Us</li>
<li>Privacy Policy</li>
</ul>
</div>
<div class="col-md-3">
<ul class="footer_box">
<h4>Support</h4>
<li>Contact Us</li>
<li>Help</li>
</ul>
</div>
<div class="col-md-3">
<ul class="footer_box">
<ul class="social">
<li class="facebook"><span> </span></li>
<li class="twitter"><span> </span></li>
<li class="instagram"><span> </span></li>
<li class="pinterest"><span> </span></li>
<li class="youtube"><span> </span></li>
</ul>
</ul>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
I was able to get it working!
By deleting the extra form tags found in the master page, the button now works.
<div id="sb-search" class="sb-search">
<form>
<input class="sb-search-input" placeholder="What are you looking for?" type="search" name="search" id="search">
<input class="sb-search-submit" type="submit" value="">
<span class="sb-icon-search"> </span>
</form>
</div>
Before I add in this part of session code, it will redirect me to BlogEntry.aspx if my username and password is correct. After I add in the session code, when I clicked the button nothing happening. Can you help me convert my session code to work in the javascript? I need to code it in the javascript and not in the code behind because I am using a html button. Because I want the design of the button, I need to do this. Unless you tell me there's a way to do it in the code behind. After login in login.aspx. It will redirect to logined.aspx and display welcome admin in the label.
Login.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
</style>
<link rel="stylesheet" type="text/css" href="stylesheets/loginstyle.css" />
<script language="javascript" type="text/javascript">
// <![CDATA[
function Button1_onclick() {
if (document.getElementById('txtUserName').value == "Admin" && document.getElementById('txtPassword').value == "123") {
//After add in session it cannot redirect START HERE
Session.Add("Username", txtUserName.Value);
Session.Add("Password", txtPassword.Value);
FormsAuthentication.SetAuthCookie(txtUserName.Value, true);
window.location.assign("BlogEntry.aspx")
//After add in session it cannot redirect END HERE
}
else
{
document.getElementById("<%=lblError.ClientID%>").innerHTML = "Name can't be blank!";
}
}
// ]]>
</script>
</head>
<body>
<div id="wrapper">
<form name="login-form" class="login-form" action="" method="post">
<div class="header">
<h1>Login Form</h1>
<span>Fill out the form below to login to my super awesome imaginary control panel.</span>
</div>
<div class="content">
<input name="username" type="text" class="input username" placeholder="Username" runat="server" id="txtUserName" />
<div class="user-icon"></div>
<input name="password" type="password" class="input password" placeholder="Password" runat="server" id="txtPassword" />
<div class="pass-icon"></div>
</div>
<div class="footer">
<input type="button" name="submit" value="Login" class="button" runat="server" id="Button1" önserverclick="Button1_Click" onclick="return Button1_onclick()" />
<asp:Label ID="lblError" runat="server" Text=""></asp:Label>
</div>
</form>
</div>
<div class="gradient"></div>
</body>
</html>
Logined.aspx
protected void Page_Load(object sender, EventArgs e)
{
//Logout.Visible = false;
string memName = (String)Session["UserName"];
lblUsername.Text = String.Concat("Welcome Guest!");
if (Session["Username"] != null && Session["Username"] != String.Empty)
{
lblUsername.Text = "Welcome, " + memName + "!";
}
}
For #Sangram
You can use html session storage or localStorage to store your key values. this will not need any server side code. The info will be there even if the user close the browser.
for browser compatibility: http://www.html5rocks.com/en/features/storage
for example: http://coding.smashingmagazine.com/2010/10/11/local-storage-and-how-to-use-it/
I've got this code for signing up users:
public partial class signup : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.Form["username"]+"SSS");
Page.Validate();
if (Request.Form["submit"] != null && Page.IsValid) {
register1();
}
}
public void register1()
{
string sql = "INSERT INTO [userinfo] ([username], [password], [email]) VALUES (N'" + Request.Form["username"] + "', N'" + Request.Form["password"] + "', N'" + Request.Form["email"] + "')";
Response.Write(sql);
Database.UpdateData(sql);
//Response.Redirect("Default.aspx");
}
It's filling my database with empty rows, I've tried simply printing Request.form and its coming up empty, I've got the names right, what going on?
Here is the html page:
<div class="grid_6">
<header class="grid_6 push_3 alpha">
<h2>הרשמה
</h2>
</header>
<!-- -->
<div class="grid_6 push_3 block alpha">
<div class="grid_6 form_block alpha omega">
<label>שם משתמש</label>
</div>
<div class="grid_6 form_block alpha omega">
<input type="text" id="username" name="username" required pattern="^\S{4,}$" runat="server" />
<span class="form_hint">שם משתמש צריך להכיל לפחות 4 תווים</span>
<asp:RegularExpressionValidator ID="valUsername" ControlToValidate="username" ValidationExpression="^\S{4,}$"
ValidationGroup="First" EnableClientScript="false" CssClass="form_hint" Style="display: inline;" ErrorMessage="שם משתמש צריך להכיל לפחות 4 תווים" runat="server" />
</div>
<div class="grid_6 alpha omega form_block">
<label>סיסמא</label>
</div>
<div class="grid_6 form_block alpha omega">
<input type="password" id="password" name="password" title="סיסמא צריכה להכיל לפחות 6 תווים" required pattern="^\S{6,}$" runat="server" />
<span class="form_hint">סיסמא צריכה להכיל לפחות 6 תווים</span>
<asp:RegularExpressionValidator ID="valPassword" ControlToValidate="password" ValidationExpression="^\S{6,}$"
ValidationGroup="First" EnableClientScript="false" CssClass="form_hint" Style="display: inline;" ErrorMessage="סיסמא צריכה להכיל לפחות 6 תווים" runat="server" />
</div>
<div class="grid_6 alpha omega form_block">
<label>וודא סיסמא</label>
</div>
<div class="grid_6 form_block alpha omega">
<input type="password" id="password2" required pattern="^\S{6,}$" runat="server" />
<span class="form_hint" id="pass2_hint">סיסמאות לא תואמות</span>
<asp:CompareValidator ID="valPasswords"
ControlToValidate="password" ControlToCompare="password2" Type="String"
ValidationGroup="First" EnableClientScript="false" CssClass="form_hint" Style="display:inline;" Text="סיסמאות לא תואמות"
runat="server" />
</div>
<div class="grid_6 alpha omega form_block">
<label>כתובת אימייל</label>
</div>
<div class="grid_6 form_block alpha omega">
<input id="email" name="email" type="text" required pattern="[^#]+#[^#]+\.[a-zA-Z]{2,6}" runat="server"/>
<span class="form_hint">התבנית התקינה לאימייל: test#test.com</span>
<asp:RegularExpressionValidator ID="valEmail" ControlToValidate="email" ValidationExpression="[^#]+#[^#]+\.[a-zA-Z]{2,6}"
ValidationGroup="First" EnableClientScript="false" CssClass="form_hint" Style="display:inline;" ErrorMessage="אימייל לא תקין" runat="server" />
</div>
<div class="grid_6 alpha omega form_block">
<label>וודא כתובת אימייל</label>
</div>
<div class="grid_6 form_block alpha omega">
<input id="email2" type="text" required pattern="[^#]+#[^#]+\.[a-zA-Z]{2,6}" runat="server"/>
<span class="form_hint" id="email2_hint">כתובות אימייל לא תואמות</span>
<asp:CompareValidator ID="valEmails"
ControlToValidate="email" ControlToCompare="email2" Type="String"
ValidationGroup="First" EnableClientScript="false" CssClass="form_hint" Style="display:inline;" Text="כתובות אימייל לא תואמות"
runat="server" />
</div>
<div class="grid_6 form_block alpha omega">
<input name="submit" type="submit" ValidationGroup="First" onclick="return validateForm()" value="שלח" />
</div>
</div>
</div>
<div class="grid_3 pull_6" id="ad">
</div>
Since the "accepted" answer provided no actual answer. This is what worked for me when I was researching an answer for myself.
when using runat="server" in an asp textbox try:
request.form(name.uniqueID)
I think you need a <form runat="server"> element wrapping your inputs.
Nevermind, problem solved, apparently when using inputs that have runat="server" attribute the method of access from the cs code is different.