Hi,

I'm quite new to Web Development. I'm creating a web site and it has a Registration Page where I managed to create the form. But when the user clicks on the 'CreateUser' button, how do I display a message on the form to show that the User is created. And also, at the moment, I don't know where the user details are being created. I wish to add the details to a Login Table in the SQL Database. How do I go about it please?

Thanks

Recommended Answers

All 29 Replies

Hi shers,

What your asking actually involves several in depth topics. If you could provide a little more information such as what framework you're using such as webforms or mvc, are you using lightswitch, do you want the message to show on a new page or maybe via ajax on the same page ect... it would help to answer your question a litte better. For example in Webforms you would do a postback or a cross page post to show a "created successfully" message. In mvc you would post to a controller action. In the meantime here are some topics you should do some reading on:

Asp.Net Forms Authentication

Asp.Net Mebership and Membership Providers.

The aspnet_regsql.exe *tool that comes with whichever version of the .Net Framework you're using.

Hi,

Thanks for your reply. I'm using .NET Framework 4 and Visual Web Developer 2010 Express. I started with creating a new Web Site which already had few pages. So with my little knowledge, I think it should be webforms. I modified the Registration Page to match my requirements, checked with the RequiredFieldValidator and everything goes well. But when I click on the 'Create User' button, the data should go into the database table. And also a message should be displayed on the same page for the user to know that the User is created.

Thanks

The default behaviour for a .Net 4 webforms application after the user is created is to log the user in and redirect to the home page. The user will know they have been logged in because it says Welcome user! [ Log Out ] in the upper right hand corner of the screen.

In the code behind file of the Register page (Register.aspx.cs) you have this code:

protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
    FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);

    string continueUrl = RegisterUser.ContinueDestinationPageUrl;
    if (String.IsNullOrEmpty(continueUrl))
    {
        continueUrl = "~/";
    }
    Response.Redirect(continueUrl);
}

If you want to change this behaviour you need to add a control to the register page to display your message and modify the code in this method to something like:

 protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
    FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);

    Label.Text = "Your user has been successfully created!";
}

With that said I think this is a bad idea. The registration process is based on wizard steps and forms. You would need to hide the registration form in Register page when the users has successfully create a users. If you just want a success page I would create a new aspx page something like UserCreated.aspx and have a message in there stating success or failure then change the above method to redirect to that page:

 protected void RegisterUser_CreatedUser(object sender, EventArgs e)
{
    FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);

    string continueUrl = RegisterUser.ContinueDestinationPageUrl;
    if (String.IsNullOrEmpty(continueUrl))
    {
        continueUrl = "~/UserCreated.aspx";
    }
    Response.Redirect(continueUrl);
}

I would recommend that you head over to asp.net and watch some of the webforms tutorial vidoes at

http://www.asp.net/web-forms/tutorials

Good luck.

Thanks very much for the advice. I would definitely use the first method you mentioned.

Btw, I have deleted the CreateUserWizard and created another on with my own labels and textboxes. For that reason, it does not work. This is the error I get.

RegisterUser: CreateUserWizardStep.ContentTemplate does not contain an IEditableTextControl with ID UserName for the username.

Here's my source page code for the registration page:

<%@ Page Title="Register" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Account_Register" %>

<asp:Content ID="HeaderContent" ContentPlaceHolderID="HeadContent" Runat="Server">
    <style type="text/css">
        .accessKey
        {
            display:none;
            position:absolute;
            z-index:5000;
            padding:3px;
            border:solid 1px black;
            background-color:#ffffe0
        }
    </style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:CreateUserWizard ID="RegisterUser" runat="server" EnableViewState="false" OnCreatedUser="RegisterUser_CreatedUser">
        <LayoutTemplate>
            <asp:PlaceHolder ID="wizardStepPlaceholder" runat="server"></asp:PlaceHolder>
            <asp:PlaceHolder ID="navigationPlaceholder" runat="server"></asp:PlaceHolder>
        </LayoutTemplate>
        <WizardSteps>
            <asp:CreateUserWizardStep ID="RegisterUserWizardStep" runat="server">
                <ContentTemplate>
                    <h3>
                        CREATE A NEW ACCOUNT
                    </h3>
                    <p>
                        Use the form below to create a new account
                    </p>
                    <span class="failureNotification">
                        <asp:Literal ID="ErrorMessage" runat="server"></asp:Literal>
                    </span>
                    <asp:ValidationSummary ID="RegisterUserValidationSummary" runat="server" CssClass="failureNotification" ValidationGroup="RegisterUserValidationGroup" ></asp:ValidationSummary>
                    <div class="accountInfo">
                        <fieldset class="register">
                            <legend>Account Information</legend>
                            <p> 
                                <asp:Label ID="lblFName" runat="server" AssociatedControlID="txtFName">Full Name:</asp:Label>
                                <asp:TextBox ID="txtFName" runat="server" CssClass="textEntry"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="FNameRequired" runat="server" ControlToValidate="txtFName"
                                    CssClass="failureNotification" ErrorMessage="Full Name is required." ToolTip="Full Name is required."
                                    ValidationGroup="RegisterUserValidationGroup">*</asp:RequiredFieldValidator>
                            </p>
                            <p> 
                                <asp:Label ID="lblEmail" runat="server" AssociatedControlID="txtEmail">Email:</asp:Label>
                                <asp:TextBox ID="txtEmail" runat="server" CssClass="textEntry"></asp:TextBox>
                                <asp:Label ID="lblMsg1" runat="server" CssClass="Info">used as login Id.</asp:Label>
                                <asp:RequiredFieldValidator ID="EmailRequired" runat="server" ControlToValidate="txtEmail"
                                    CssClass="failureNotification" ErrorMessage="Email is required." ToolTip="Email is required."
                                    ValidationGroup="RegisterUserValidationGroup">*</asp:RequiredFieldValidator>               
                                <asp:RegularExpressionValidator ID="EmailCheck" runat="server" ControlToValidate="txtEmail"
                                    CssClass="failureNotification" Display="Dynamic" ErrorMessage="Please enter a valid email address."
                                    ValidationGroup="RegisterUserValidationGroup"
                                    ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>  
                            </p>
                            <p>
                                <asp:Label ID="lblPwd" runat="server" AssociatedControlID="txtPwd">Password:</asp:Label>
                                <asp:TextBox ID="txtPwd" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="txtPwd"
                                    CssClass="failureNotification" ErrorMessage="Password is required." ToolTip="Password is required."
                                    ValidationGroup="RegisterUserValidationGroup">*</asp:RequiredFieldValidator>
                                <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" Display="Dynamic" ControlToValidate="txtPwd"
                                    ErrorMessage="Password must be 6-12 nonblank characters."
                                    ValidationGroup="RegisterUserValidationGroup" ValidationExpression="[^\s]{6,12}" ></asp:RegularExpressionValidator>
                            </p>
                            <p>
                                <asp:Label ID="lblCPwd" runat="server" AssociatedControlID="txtCPwd">Confirm Password:</asp:Label>
                                <asp:TextBox ID="txtCPwd" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server" ControlToValidate="txtCPwd"
                                    CssClass="failureNotification" Display="Dynamic" ErrorMessage="Confirm Password is required"
                                    ToolTip="Confirm Password is required." ValidationGroup="RegisterUserValidationGroup">*</asp:RequiredFieldValidator>
                                <asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="txtPwd" ControlToValidate="txtCPwd"
                                    CssClass="failureNotification" Display="Dynamic" ErrorMessage="The Password and Confirmation Password must match."
                                    ValidationGroup="RegisterUserValidationGroup">*</asp:CompareValidator>
                            </p>
                            <p>
                                <asp:Label ID="lblFile" runat="server" AssociatedControlID="FileUpload">Upload Photo:</asp:Label>
                                <asp:FileUpload id="FileUpload" runat="server" CssClass="textEntry"></asp:FileUpload> 
                                <asp:RegularExpressionValidator ID="ImgCheck" runat="server" ControlToValidate="FileUpload"
                                    CssClass="failureNotification" Display="Dynamic" ErrorMessage="Only image files are allowed."
                                    ValidationGroup="RegisterUserValidationGroup"
                                    ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.jpg|.jpeg)$">*</asp:RegularExpressionValidator> 
                                <br />
                                <asp:Label ID="lblMsg2" runat="server" CssClass="Info">jpg or jpeg files of up to 2MB</asp:Label>           
                            </p>
                            <p>
                                <asp:Label ID="lblCreateUserResult" runat="server"></asp:Label>
                            </p>
                        </fieldset>
                        <p class="submitButton">
                            <asp:Button ID="btnCreateUser" runat="server" CommandName="MoveNext" Text="Create User"
                                ValidationGroup="RegisterUserValidationGroup" ></asp:Button>
                        </p>
                    </div>
                </ContentTemplate>
            </asp:CreateUserWizardStep>            
        </WizardSteps>
    </asp:CreateUserWizard>
</asp:Content>

Please help.

Thanks

The error message is pretty straight forward. The wizard is looking for a field with the id of "UserName" and you don't have one:

CreateUserWizardStep.ContentTemplate does not contain an IEditableTextControl with ID UserName for the username

Since you have this field it seems like you are trying to use the email as the username?

<asp:TextBox ID="txtEmail" runat="server" CssClass="textEntry"></asp:TextBox>

Adding this line will fix the current error:

<asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox>

But I wish to use the email to login. So how do I go about it please?

Thanks

You need to scrap the default registration form that uses CreateUserWizard and code it manually passing the email in as the username to membership.create.

The new form would have an email field, two password fields with validators, a button plus the label for you success message.

On the button click, in the code behind file, you would do something like this:

protected void createuser_click(object sender, EventArgs e) {
    try {
        var email = this.Email.Text; //Your email field id should = "Email"
        var password = this.Password.Text; //password field id should = "Password"
        var user = Membership.CreateUser(email, password, email);
        this.MessageLabel = "Successfully created user."
    }
    catch (Exception ex) {
        //handle your exceptions
    }
}

Asp.net is secure programme and we can easily create admin panel and user panel in it.
Thanks

@woomichal

Is that a question or are you answering for shers or just making a random observation?

thanks for sharing

thanks for sharing

thanks for sharing

Is that a question or are you answering for shers or just making a random observation?

Is that a question or are you answering for shers or just making a random observation?

Is that a question or are you answering for shers or just making a random observation?

thanks for sharing

thanks for sharing

androtheos, thanks for the code. I added it to the click event of the button, but there is some design issue and I can't figure out what's wrong as I'm just a novice. The click is not working. I've attached a snapshot of the design and how it looks on the browser. Please help.

Capture8Capture11

Thanks

Lools like you have a malformed tag. Can you share the code in aspx file?

Actually if you copied my code snippet the problem is likely in this line:

this.MessageLabel = "Successfully created user."

it should be:

this.MessageLabel.Text = "Successfully created user."

Here's my code in the Register.aspx file.

<%@ Page Title="Register" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Account_Register" %>

<asp:Content ID="HeaderContent" ContentPlaceHolderID="HeadContent" Runat="Server">
    <style type="text/css">
        .accessKey
        {
            display:none;
            position:absolute;
            z-index:5000;
            padding:3px;
            border:solid 1px black;
            background-color:#ffffe0
        }
        .style11
        {
            width: 341px;
        }
        .style12
        {
            text-align: right;
        }
    </style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Create a New Account
    </h2>
    <p>
        Use the form below to create a new account.
    </p>
    <span class="failureNotification">
        <asp:Literal ID="FailureText" runat="server"></asp:Literal>        
    </span>
    <div class="accountInfo">
        <fieldset class="register">
            <legend>Account Information</legend>
            <table style="width: 510px; height: 200px">
                <tr>
                    <td>
                        <asp:Label ID="FullNameLabel" runat="server" AssociatedControlID="FullName">Full Name:</asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="FullName" runat="server" CssClass="textEntry" height="19px" 
                            width="309px"></asp:TextBox>
                    </td>
                    <td>
                        <asp:RequiredFieldValidator ID="FullNameRequired" runat="server" ControlToValidate="FullName" 
                            CssClass="failureNotification" ErrorMessage="Full Name is required." 
                            Display="Dynamic" ToolTip="Full Name is required.">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                       <asp:Label ID="EmailLabel" runat="server" AssociatedControlID="Email">Email:</asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="Email" runat="server" CssClass="textEntry" height="19px" 
                            width="309px"></asp:TextBox>
                    </td>
                    <td>
                        <asp:RequiredFieldValidator ID="EmailRequired" runat="server" ControlToValidate="Email" 
                            CssClass="failureNotification" ErrorMessage="Email is required." 
                            Display="Dynamic" ToolTip="Email is required.">*</asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="EmailCheck" runat="server" 
                            CssClass="failureNotification" Display="Dynamic" 
                            ErrorMessage="Please enter a valid email address." 
                            ControlToValidate="Email">*</asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="Password" runat="server" CssClass="textEntry" height="19px" 
                            TextMode="Password" width="309px"></asp:TextBox>
                    </td>
                    <td>
                        <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" 
                            CssClass="failureNotification" ErrorMessage="Password is required." 
                            Display="Dynamic" ToolTip="Password is required.">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="ConfirmPasswordLabel" runat="server" AssociatedControlID="ConfirmPassword">Confirm Password:</asp:Label>
                    </td>
                    <td>
                        <asp:TextBox ID="ConfirmPassword" runat="server" CssClass="textEntry" 
                            height="19px" TextMode="Password" width="309px"></asp:TextBox>
                    </td>
                    <td>
                        <asp:RequiredFieldValidator ID="ConfirmPasswordRequired" runat="server" ControlToValidate="FullName" 
                            CssClass="failureNotification" 
                            ErrorMessage="Confirm Password is required." Display="Dynamic" 
                            ToolTip="Confirm Password is required.">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="PhotoUploadLabel" runat="server" AssociatedControlID="PhotoUpload">Upload Photo:</asp:Label>
                    </td>
                    <td>
                        <asp:FileUpload ID="PhotoUpload" runat="server" CssClass="textEntry" 
                            Height="19px" Width="309px"></asp:FileUpload>
                    </td>
                </tr>
                </table>
        </fieldset>
        <p class="submitButton">
            <asp:Button ID="CreateUser" runat="server" CssClass="textEntry" 
                Text="Create User" onclick="CreateUser_Click" />
        </p>
        <p>

            <asp:Label ID="MessageLabel" runat="server"></asp:Label>

        </p>
    </div>
</asp:Content>

Thanks

I don't see the issue. Maybe you can zip your project and upload it so I can take a look?

I've attached the zipped project. Please have a look.

Thanks

The reason the button wasn't working is because you had a regular expression validator on the email field withough a ValidationExpression in it so it was always tripping the validator. You could tell by the red * next to the email field.

Your validator should look something like this:

<asp:RegularExpressionValidator ID="EmailCheck" runat="server" 
                            CssClass="failureNotification" Display="Dynamic" 
                            ErrorMessage="Please enter a valid email address." 
                            ValidationExpression="^((([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.(af|ax|al|dz|as|ad|ao|ai|aq|ag|ar|am|aw|au|at|az|bs|bh|bd|bb|by|be|bz|bj|bm|bt|bo|ba|bw|bv|br|io|bn|bg|bf|bi|kh|cm|ca|cv|ky|cf|td|cl|cn|cx|cc|co|km|cg|cd|ck|cr|ci|hr|cu|cy|cz|dk|dj|dm|do|ec|eg|sv|gq|er|ee|et|fk|fo|fj|fi|fr|gf|pf|tf|ga|gm|ge|de|gh|gi|gr|gl|gd|gp|gu|gt| gg|gn|gw|gy|ht|hm|va|hn|hk|hu|is|in|id|ir|iq|ie|im|il|it|jm|jp|je|jo|kz|ke|ki|kp|kr|kw|kg|la|lv|lb|ls|lr|ly|li|lt|lu|mo|mk|mg|mw|my|mv|ml|mt|mh|mq|mr|mu|yt|mx|fm|md|mc|mn|ms|ma|mz|mm|na|nr|np|nl|an|nc|nz|ni|ne|ng|nu|nf|mp|no|om|pk|pw|ps|pa|pg|py|pe|ph|pn|pl|pt|pr|qa|re|ro|ru|rw|sh|kn|lc|pm|vc|ws|sm|st|sa|sn|cs|sc|sl|sg|sk|si|sb|so|za|gs|es|lk|sd|sr|sj|sz|se|ch|sy|tw|tj|tz|th|tl|tg|tk|to|tt|tn|tr|tm|tc|tv|ug|ua|ae|gb|us|um|uy|uz|vu|ve|vn|vg|vi|wf|eh|ye|zm|zw|com|edu|gov|int|mil|net|org|biz|info|name|pro|aero|coop|museum|arpa))|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$"        
                            ControlToValidate="Email" >* Please enter a valid email address</asp:RegularExpressionValidator>

The regex being used was copied from regexlib.com.

Once you put his in place everything works fine.

Also I noticed that debugging wasn't enable in the project. Do yourslef a favor and read up on how to use debugging in Visual Studio it will make your life alot easier if you intend to keep coding. This is a mistake alot of newbie coders make, trying to debug with ouput error messages and popup windows. Don't do that. Learn debugging as early as possible.

Good Luck.

If this fixes your registration form please click the solved button at the bottom of the last post. Thanks.

That great! I've anyway used the property grid to set the ValidationExpression. And all works fine. But I've got another problem now. If the user is already created, it doesn't show up in the ValidationSummary. How do I get to show the error there?

Thanks

Sorry, I think I've got it to work. Here's the code:

protected void CreateUserButton_Click(object sender, EventArgs e)
    {
        try
        {
            var email = this.Email.Text;
            var password = this.Password.Text;
            var user = Membership.CreateUser(email, password, email);
            this.MessageLabel.Text = "Successfully created user.";
        }
        catch (Exception ex)
        {
            if (ex.Message != null)
            {
                CustomValidator err=new CustomValidator();
                err.CssClass = "failureNotification";
                err.IsValid=false;
                err.ErrorMessage=ex.Message.ToString();
                Page.Validators.Add(err);
            }
        }
    }

Is this correct?

Thanks

Yes that will work.

You want to be careful about catching all exceptions and showing them to the user though, this can be a big security risk. You are better off catching the exception and giving the user a generic message ("An error has occurred, our staff has been notified.") then sending an email off to an administrator or I.T. staff member who can try to fix the actual issue.

Handling the exception came in when I noticed that if the user already exists, then it goes to the catch and the exception message is that the user already exists. This error has to be notified to the user. But the other kinds of errors never came to my mind though. But don't really know what other kinds of errors will occur and how to handle them.

BTW, I've enabled debugging. Thanks very much for the info and guidance.

Thanks

I'm glad you got it to work shers.

Please mark this thread as solved. There is a button at the bottom of the last post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.