3. Insert In ASP.NET MVC 5 using Ado.net

In these article we are going to learn Insert data into databaseUsing this article uses ADO.Net commands to work with SQL Server Database. 

I promise, you will be able to write your own customize code in MVC . If you are beginners or trying to learn MVC don't worry you easy to understand.


I create MVC application for Insert operation . just create project following steps.
File --->  New -->Project-->Web--> Choose Asp.net web Application(.Net Framework)--> MVC









Step 1:  Create first model class StudentModel.cs class.

using System.ComponentModel.DataAnnotations;

namespace CurdOperationAdo.Models

{
    public class StudentModel
    {
        [Display(Name = "Id")]
        public int Id { get; set; }
        [Required(ErrorMessage = "First name is required.")]
        public string Name { get; set; }
        [Required(ErrorMessage = "City is required.")]
        public string City { get; set; }
        [Required(ErrorMessage = "Address is required.")]
        public string Address { get; set; }
    }
}


Step 2: Create Database, Table and Store Procedure

CREATE TABLE [dbo].[StudentReg]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY
    [Name] NVARCHAR(50) NULL, 
    [City] NVARCHAR(50) NULL, 
    [Address] NVARCHAR(100) NULL
)

Insert Records – Store Procedure
Create procedure [dbo].[AddNewStudent]  
(  
   @Name nvarchar (50),  
   @City nvarchar (50),  
   @Address nvarchar (100)  
)  
as  
begin  
   Insert into StudentReg values(@Name,@City,@Address)  
End


After Creating all Store Procedure 

Step 3: Create in web.config file to connect to Database .

<connectionStrings>
<add name="DBConn" connectionString="Data Source=.;
Initial Catalog=fly; Integrated Security=True;Pooling=False"/>
</connectionStrings>

Step 4: Create StudentDBHandle.cs class for handling all the database operations.

1. Right click on Models folder  Add  Class. Create new class StudentDBHandle.cs

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace CurdOperationAdo.Models
{
    public class StudentDBHandle
    {
        private SqlConnection con;
        private void connection()
        {
            string constring = ConfigurationManager.ConnectionStrings["DBConn"].ToString();
            con = new SqlConnection(constring);
        }

        // **************** ADD NEW STUDENT*********************

        public bool AddStudent(StudentModel emodel)
        {
            connection();
            SqlCommand cmd = new SqlCommand("AddNewStudent", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Name", emodel.Name);
            cmd.Parameters.AddWithValue("@City", emodel.City);
            cmd.Parameters.AddWithValue("@Address", emodel.Address);
            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
                return true;
            else
                return false;
        }
    }
}


Step 5:  Add Action Method in HomeController.

Open StudentController and add the following action methods. Here, I am going to add Create action methods for following purpose.

 Create() - Adding New ActionResult

using System.Web.Mvc;
using CurdOperationAdo.Models;

namespace CurdOperationAdo.Controllers
{
    public class HomeController : Controller
    {
        
        // 1. *************ADD NEW STUDENT ******************
        // GET: Student/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Home/Create
        [HttpPost]
        public ActionResult Create(StudentModel emodel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                   StudentDBHandle sdb = new StudentDBHandle();
                    if (sdb.AddStudent(emodel))
                    {
                        ViewBag.Message = "Student Details Added Successfully";
                        ModelState.Clear();
                    }
                }
                return View();
            }
            catch
            {
                return View();
            }
        }


 Step 6Create Partial View from Action Method.

     Right Click on Create() Action Method and Select Add View

@model MVCInjectionModel.EmployeeModel

@{

    ViewBag.Title = "Create";
}

<h2>Create</h2>



@using (Html.BeginForm()) 

{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>EmployeeModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <divclass="form-group">

            @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
            </div>
        </div>

        <divclass="form-group">

            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <divclass="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">

            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>

    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {

    @Scripts.Render("~/bundles/jqueryval")
}

Step 7: Run the project

localhost:42555/Home/create write and Hit Enter the class.

localhost:42555 is port number different machine to machine.