In this tutorial I am going to demonstrate to create registration form using entity framework code first approach in asp.net MVC.In this demonstration I also implement cascade drop-downs(Country and state).
Database Tables:
Employee
State
In this example I am using three tables , employees state and country. state and country tables are used for cascade dropdown and employee table is used to save employee data.
Let’s start
- Create a new Project. Open Visual Studio 2013.
- Go to “File” => “New” => “Project…”.
- Select “Web” in installed templates.
- Select “ASP.NET MVC Web Application”.
- Enter the Name and choose the location.
- Click “OK”.
Following is the database script of country , state and employees.
CREATE TABLE [dbo].[country]( [country_id] [int] IDENTITY(1,1) NOT NULL, [country_name] [varchar](50) NOT NULL, [country_abbrev] [varchar](3) NOT NULL, PRIMARY KEY CLUSTERED ( [country_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO CREATE TABLE [dbo].[state]( [state_id] [int] IDENTITY(1,1) NOT NULL, [country_id] [int] NULL, [state_name] [varchar](50) NOT NULL, [state_abbrev] [varchar](2) NOT NULL, CONSTRAINT [PK__state__81A47417FDC731AD] PRIMARY KEY CLUSTERED ( [state_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[state] WITH CHECK ADD CONSTRAINT [FK_state_country] FOREIGN KEY([country_id]) REFERENCES [dbo].[country] ([country_id]) GO CREATE TABLE [dbo].[Employee]( [empid] [int] IDENTITY(1,1) NOT NULL, [empname] [varchar](50) NULL, [empfathername] [varchar](50) NULL, [empsalary] [int] NULL, [country_name] [varchar](50) NULL, [state_name] [varchar](50) NULL, [email] [varchar](50) NULL, [accountactivated] [bit] NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ( [empid] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO
now first we create models for country ,state and employee.
we will create 3 classes in models folder.
Employee
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace EF.Models { [Table("Employee")] public class Employee { [Key] public int empid { get; set; } public string empname { get; set; } public string empfathername { get; set; } public int empsalary { get; set; } public string country_name { get; set; } public string state_name { get; set; } public string email { get; set; } public bool? accountactivated { get; set; } } }
Country
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace EF.Models { [Table("Country")] public class Country { [Key] public int country_id { get; set; } public string country_name { get; set; } } }
State
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace EF.Models { [Table("State")] public class State { public int country_id { get; set; } [Key] public int state_id { get; set; } public string state_name { get; set; } } }
to implement Insert operations in database Table Employee using entity framework code first .we have to define data context class which will inherit the DbContext.
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace EF.Models { public class DataContext :DbContext { public DataContext() : base("conn") { } public DbSet<Employee> Employees { get; set; } public DbSet<Country> Countries { get; set; } public DbSet<State> States { get; set; } } }
define database connection string in web.config file.
<connectionStrings> <add name="conn" connectionString="server=JOHN\YOGESHDOTNET;database=ganesha;integrated security=SSPI" providerName="System.Data.SqlClient"/> </connectionStrings>
Home Controller
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using EF.Models; namespace EF.Controllers { public class HomeController : Controller { private DataContext db = new DataContext(); static string Cname = ""; // GET: /Home/ public ActionResult Index() { return View(db.Employees.ToList()); } // GET: /Home/Details/5 public ActionResult Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Employee employee = db.Employees.Find(id); if (employee == null) { return HttpNotFound(); } return View(employee); } // GET: /Home/Create public ActionResult Create() { ViewBag.Countries = db.Countries.ToList(); return View(); } private IList<State> GetState(int Countryid) { var data = db.States.Where(m => m.country_id == Countryid).ToList(); return data; } [AcceptVerbs(HttpVerbs.Get)] public JsonResult LoadStatesByCountryId(string Countryid, string cn) { Cname = cn; var StateList = this.GetState(Convert.ToInt32(Countryid)); var StatesData = StateList.Select(m => new SelectListItem() { Text = m.state_name, Value = m.state_id.ToString(), }); return Json(StatesData, JsonRequestBehavior.AllowGet); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include="empid,empname,empfathername,empsalary,country_name,state_name,email")] Employee employee, FormCollection frm) { if (ModelState.IsValid) { Employee em = new Employee(); em.country_name = Cname; int sname =Convert.ToInt16(frm["state_name"]); em.state_name = db.States.Single(x => x.state_id == sname).state_name; // em.state_name = frm["state_name"]; em.empname = frm["empname"]; em.empfathername = frm["empfathername"]; em.empsalary =Convert.ToInt32(frm["empsalary"]); em.email = frm["email"]; db.Employees.Add(em); db.SaveChanges(); return RedirectToAction("Index"); } return View(employee); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
create an Create.cshtml in create action
Create.cshtml
@model EF.Models.Employee @{ ViewBag.Title = "Create"; } <h2>Create</h2> <script type="text/javascript"> $(document).ready(function () { $("#dd_Country").change(function () { var countryId = $(this).val(); // var d = $("#dd_Country").val($(this).text()); var txt = $("#dd_Country option:selected").text(); $("#span1").text(txt); $.getJSON("../Home/LoadStatesByCountryId", { Countryid: countryId, cn: txt }, function (classesData) { var select = $("#ddState"); select.empty(); select.append($('<option/>', { value: 0, text: "Select a State" })); $.each(classesData, function (index, itemData) { select.append($('<option/>', { value: itemData.Value, text: itemData.Text })); }); }); }); }); </script> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Employee</h4> <hr /> @Html.ValidationSummary(true) <div class="form-group"> @Html.LabelFor(model => model.empname, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.empname, new { @class="form-control" }) @Html.ValidationMessageFor(model => model.empname) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.empfathername, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.TextBoxFor(model => model.empfathername, new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.empfathername) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.empsalary, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.empsalary) @Html.ValidationMessageFor(model => model.empsalary) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.country_name, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("Countries", new SelectList(ViewBag.Countries as System.Collections.IEnumerable, "country_id", "country_name"),"Select a Country", new { id = "dd_Country" }) @Html.ValidationMessageFor(model => model.country_name) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.state_name, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownListFor(Model => Model.state_name, new SelectList(Enumerable.Empty<SelectListItem>(), "state_id", "statename"), "Select a State", new { id = "ddState" }) <span id="span1" name="span1"></span> </div> </div> <div class="form-group"> @Html.LabelFor(model => model.email, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.email) @Html.ValidationMessageFor(model => model.email) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-primary " /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div> <script src="~/Scripts/jquery-1.10.2.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Note: Dont forget to pass bootstrap.css and jquery reference in Layout.cshtml
Output
Could you please share complete Registration page like Gender in Radio button and country state in dropdownlist with save and submit button