Monday, April 13, 2015

Create a user registration form in MVC

Introduction: In this article today I am going explain how to create a user registration form in asp.net MVC razor
Create a user registration form in MVC

Description:

Please follow the below given steps to create a complete user registration form:
Step 1: Create a new project
To create a new project Go to File >> New >> project >> Select asp.net MVC application>> Enter application name >> Click on Ok button >> Select Empty and hit on Ok button.

Step 2: Add class to Model
To add class Right click on Models folder >> Add >> Select Class and Enter class name. In this project I add three Classes
User_Registration.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class User_Registration
    {
        [Key]
        public int Id { get; set; }
       [Required(ErrorMessage="Please Enter UserName")]
        public string User_Name { get; set; }
          [Required(ErrorMessage = "Please Enter First Name")]
        public string First_Name { get; set; }
      [Required(ErrorMessage = "Please Enter Last Name")]
        public string Last_Name { get; set; }
       [DataType(DataType.Upload)]
        public string Profile_Image { get; set; }
    [Required(ErrorMessage = "Please Enter Password")]
        public string Password { get; set; }
        [RegularExpression(@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$",ErrorMessage = "Please Enter Email ID")]
        public string EmailId { get; set; }
       [Required(ErrorMessage = "Please Enter Gender")]
        public string Sex { get; set; }
        [Required(ErrorMessage = "Please Select Qualification")]
        [ForeignKey("Master_Qualification")]
        public int EducationId { get; set; }
       [Required(ErrorMessage = "Please Select Country")]
        [ForeignKey("Master_Country")]
        public int CountryId { get; set; }
       [Required(ErrorMessage = "Please Enter Phone No")]
        public int Phone_No { get; set; }
     [Required(ErrorMessage = "Please Select the terma & Conditions")]
        public bool Terms { get; set; }

        public virtual Master_Country Master_Country { get; set; }
        public virtual Master_Qualification Master_Qualification { get; set; }
    }

 Master_Qualification.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class Master_Qualification
    {
        [Key]
        public int Id { get; set; }
         [Required]
        public string Qualification { get; set; }

        public virtual ICollection<User_Registration> User_Registrations { get; set; }
    }

Master_Country.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
   public class Master_Country
    {
        [Key]
        public int Id { get; set; }
         [Required]
        public string Country_Name { get; set; }

        public virtual ICollection<User_Registration> User_Registrations { get; set; }
    }

Step 3: Add classes DBset to project DBContext
I add another class to Models folder named ProjectContext.cs
using System.Data.Entity;

public class ProjectContext :DbContext
    {
        public ProjectContext()
            : base("name=ProjectConnectionString")
        {
        }
        public DbSet<User_Registration> User_Registrations { get; set; }
        public DbSet<Master_Qualification> Master_Qualifications { get; set; }
        public DbSet<Master_Country> Master_Country { get; set; }
    }
Note: Firstly install the Entity Framework. Install-Package EntityFramework

Step 4: Add ConnectionString
Go to web.config file and add a ConnectionString :
  <connectionStrings>
    <add name="ProjectConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\UserTestDatabase.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

Step 5: Add a controller to project
Right click on the Controllers folder >> Add >> Select Controller.  Add an empty Controller to Project UserRegistrationController.cs
using UserRegistration.Models;
using System.IO;

public class UserRegistrationController : Controller
    {
        private ProjectContext db = new ProjectContext(); 
      
        public ActionResult Create()
        {
            ViewBag.CountryId = new SelectList(db.Master_Country, "Id", "Country_Name");
            ViewBag.EducationId = new SelectList(db.Master_Qualifications, "Id", "Qualification");
            return View();
        }       

        [HttpPost]
        public ActionResult Create(User_Registration user_registration)
        {
            if (ModelState.IsValid)
            {
                HttpPostedFileBase file = Request.Files["fileupload"];
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var guid = Guid.NewGuid().ToString();
                    var path = Path.Combine(Server.MapPath("~/uploads"), guid + fileName);
                    file.SaveAs(path);
                    string fl = path.Substring(path.LastIndexOf("\\"));
                    string[] split = fl.Split('\\');
                    string newpath = split[1];
                    string imagepath = "~/uploads/" + newpath;
                    user_registration.Profile_Image = imagepath;
                    db.User_Registrations.Add(user_registration);
                    db.SaveChanges();
                    TempData["Success"] = "You have been Successfully Register to our Website";
                    return RedirectToAction("Create");                 
                }
            
            }

            ViewBag.CountryId = new SelectList(db.Master_Country, "Id", "Country_Name", user_registration.CountryId);
            ViewBag.EducationId = new SelectList(db.Master_Qualifications, "Id", "Qualification", user_registration.EducationId);
            return View(user_registration);
        }
     
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
I have added MasterCountryController.cs and MasterQualificationController.cs Controller with CRUD functionality.

Step 6: Add a View
Right Click on Create and add a strogly typed view for User_Registration.cs Model class.
@model UserRegistration.Models.User_Registration

@{
    ViewBag.Title = "Create";
}
<style>
    .editor-label
    {
        float:left;
         margin: 15px 50px 0 0;
  width: 200px;
    }
    .editor-field
    {
       margin-top: 15px;
    }
</style>
<h2>Create</h2>

@using (Html.BeginForm("Create","UserRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)


    <fieldset>
        <legend>User Registration</legend>

        <div class="editor-label">
           UserName
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.User_Name)
            @Html.ValidationMessageFor(model => model.User_Name)
        </div>

        <div class="editor-label">
           First Name
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.First_Name)
            @Html.ValidationMessageFor(model => model.First_Name)
        </div>

        <div class="editor-label">
            Last Name
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Last_Name)
            @Html.ValidationMessageFor(model => model.Last_Name)
        </div>

        <div class="editor-label">
           Upload Profile Image
        </div>
        <div class="editor-field">
            <input type="file" name="fileupload" />
            @Html.ValidationMessageFor(model => model.Profile_Image)
        </div>

        <div class="editor-label">
          Enter Password
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <div class="editor-label">
          Enter EmailId
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EmailId)
            @Html.ValidationMessageFor(model => model.EmailId)
        </div>

        <div class="editor-label">
          Gender
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Sex)
            @Html.ValidationMessageFor(model => model.Sex)
        </div>

        <div class="editor-label">
           Qualification
        </div>
        <div class="editor-field">
            @Html.DropDownList("EducationId", "--Select--")
            @Html.ValidationMessageFor(model => model.EducationId)
        </div>

        <div class="editor-label">
           Country
        </div>
        <div class="editor-field">
            @Html.DropDownList("CountryId", "--Select--")
            @Html.ValidationMessageFor(model => model.CountryId)
        </div>

        <div class="editor-label">
           Phone No.
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Phone_No)
            @Html.ValidationMessageFor(model => model.Phone_No)
        </div>

        <div class="editor-label">
          Accept the Terms & Conditions
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Terms)
            @Html.ValidationMessageFor(model => model.Terms)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
            @if (TempData["Success"] != null)
{
    <div class="success">
        <p>@TempData["Success"].ToString()</p>
    </div>
}
    </fieldset>
}

Now build the project and run.
Download

No comments:

Post a Comment