06 July 2016 Sudhanshu Ranjan 675

How to save data in database using MVC in asp.net

This is very common query while you start to learn MVC and you want to insert data in database. I am sharing this article that will help you. Please follow the steps.
 

Step 1 :  Firstly you should have to install Visual studio and MVC, SQL Server in your PC. Then You will be create a sample MVC Internet application. If you are new in MVC then you should follow the same name like in below screenshot which will help more for better understanding.

 

Step 2 : Then, you will create a sample database and have create a table. Run the below script in SQL Server. Database Name would be "TestDatabase".

 

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
	[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeName] [varchar](50) NULL,
	[Salary] [int] NULL,
	[Gender] [varchar](50) NULL,
	[Address] [varchar](250) NULL,
	[RegistrationDate] [datetime] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
	[EmployeeId] 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

Step 3 : You should add Database.edmx file and have to configure the table with database. Once you will complete the steps using Wizard then you will add Model Class.

Step 4 :  Then, You have to create a Model class and have to add following code.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace SampleApplication.Models
{
    public class EmployeeModels
    {
        public int EmployeeId { get; set; }

        //[Required] attribute marked as mandatory field.
        [Required]
        public string EmployeeName { get; set; }
        [Required]
        public int Salary { get; set; }
        [Required]
        public string Gender { get; set; }
        [Required]
        public string Address { get; set; }
        [Required]
        public DateTime RegistrationDate { get; set; }
    }
}

 

Step 5 :  Then you should add the new Controller and have to put the below code.

using SampleApplication.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SampleApplication.Controllers
{
    public class EmployeeController : Controller
    {
        TestDatabaseEntities _db = new TestDatabaseEntities();
        //
        // GET: /Employee/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]// By default
        public ActionResult AddEmployee()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddEmployee(EmployeeModels model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Employee objEmployee = new Employee();
                    objEmployee.EmployeeName = model.EmployeeName;
                    objEmployee.Address = model.Address;
                    objEmployee.Gender = model.Gender;
                    objEmployee.Salary = model.Salary;
                    objEmployee.RegistrationDate = model.RegistrationDate;
                    _db.Employees.Add(objEmployee);
                    _db.SaveChanges();
                    return RedirectToAction("AddEmployee", "Employee");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(model);
            }
            return View(model);
        }

    }
}

 

Step 6 : Then, You should create Views regarding following controller and placed the following code inside the Views.

@model SampleApplication.Models.EmployeeModels
@{
    ViewBag.Title = "AddEmployee";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Add Employee Form</h2>

<div>
    @using (Html.BeginForm("AddEmployee", "Employee", FormMethod.Post))
    {
        <div>
            @Html.ValidationSummary()
        </div>
        <div>
            @Html.LabelFor(x => x.EmployeeName)
            @Html.EditorFor(x => x.EmployeeName)
        </div>
        <div>
            @Html.LabelFor(x => x.Address)
            @Html.EditorFor(x => x.Address)
        </div>
        <div>
            @Html.LabelFor(x => x.Gender)
            @Html.EditorFor(x => x.Gender)
        </div>
        <div>
            @Html.LabelFor(x => x.Salary)
            @Html.EditorFor(x => x.Salary)
        </div>
        <div>
            @Html.LabelFor(x => x.RegistrationDate)
            @Html.EditorFor(x => x.RegistrationDate)
        </div>        
        <div>
            <input type="submit" name="submit" value="Submit Form" />

        </div>
    }
</div>

 

Step 7 : Now, You should made some change in RouteConfig file which will place in App_Start folder.

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Employee", action = "AddEmployee", id = UrlParameter.Optional }
            );
        }

 

Now Finally you will get the below screen where you can put the record and save the value in database.

 

 

Please feel free to ask any doubt during this steps. Thanks !!

 

You can share at :

About Author
Sudhanshu Kumar Ranjan | Lead Engineer at HCL Technologies | Expertise in Microsoft Technology | Author | Blogger | Programmer
Know More
Connect with him on Facebook | Google+ | LinkedIn | Twitter

Recommended Post

Leave a comment

About Dotnet Cube

It's my blog - Dotnet Cube, where you will learn and get solutions about programming, web designing and development. I started this website to share my knowledge and experience which might help someone.

You can get more details about me and my blog at About Us page.

Subscribe Newsletter

Subscribe to our monthly newsletter to get the latest industry news, Media Group updates and our current specials.

Follow On Us...

Home | About | Advertise | Copyrights | Privacy | Contact | Admin

Copyrights © 2015-2017 dotnetcube.com. All rights reserved