[10 Steps] CRUD Operation In MVC Using Ado.Net Step By Step

CRUD Operation In MVC Using Ado.Net Step By Step: In this tutorial, we are going to develop the Create Read Update Delete (CRUD) Operation.

asp.net mvc registration form


Prerequisites

  1. Basic SQL Query Knowledge
  2. SQL Connection
  3. Razor Page
  4. C#
Make Sure to Follow every step carefully to achive the CRUD Operation


Step #1

Create a table from the given SQL Script.

create database dotnet_tutorial

use dotnet_tutorial

 

CREATE TABLE [dbo].[tbl_customer](

       [customer_id] [bigint] IDENTITY(1,1) NOT NULL,

       [customer_name] [varchar](200) NOT NULL,

       [address_text] [varchar](600) NULL,

       [contact_no] [varchar](50) NULL,

       [email] [varchar](500) NULL,

       [password] [varchar](500) NULL,

 )

Step #2

Create a procedure

 

Create Procedure [dbo].[UserRegistration]

@action int,

@customer_id int=null,

@customer_name varchar(200)= NULL,

@address_text varchar(600) =NULL,

@contact_no varchar(50)= NULL,

@email varchar(500) =NULL,

@password varchar(500)= NULL            

as                  

  Begin  

              if(@action=1)--Insert

                     BEGIN

              insert into tbl_customer(customer_name,address_text,contact_no,email,password)

              values (@customer_name,@address_text,@contact_no,@email,@password)

              Select 1 StatusCode, 'Record Saved !' as Msg

              END

              ELSE  if(@action=2)--Get

                     BEGIN

              Select * from tbl_customer

              END

              ELSE  if(@action=3)--Edit

                     BEGIN

              Select * from tbl_customer where customer_id=@customer_id

              END

              ELSE  if(@action=4)--Update

              BEGIN

              update tbl_customer

                      SET customer_name=@customer_name,

                          address_text=@address_text,

                             contact_no=@contact_no,

                             email=@email,

                             password=@password

              Where

                          customer_id=@customer_id

                      Select 1 StatusCode, 'Record Updated !' as Msg

              END

  End


Step #3

Create a DataLayer.cs Class in Models Folder by Right click on Models Folder

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Web;

 

namespace MyFirstApp.Models

{

    public class DataLayer

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MYCON"].ConnectionString);

        public DataTable ExecProc(string ProName, SqlParameter[] Param)

        {

            DataTable dt = new DataTable();

            try

            {

                con.Open();

                SqlCommand cmd = new SqlCommand(ProName, con);

                cmd.CommandType = CommandType.StoredProcedure;

                foreach (SqlParameter prm in Param)

                {

                    cmd.Parameters.Add(prm);

                }

                SqlDataAdapter adp = new SqlDataAdapter(cmd);

                adp.Fill(dt);

            }

            catch (Exception)

            {

            }

            finally

            {

                con.Close();

            }

            return dt;

        }

    }

}


Step #4

Create a MiddleLayer.cs Class in Models Folder by Right click on Models Folder.

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Web;

 

namespace MyFirstApp.Models

{

    public class MiddleLayer

    {

        DataLayer objDL = new DataLayer();

        public DataTable CustomerCRUD(Customer Objp, string ProcName)

        {

            DataTable dtt = new DataTable();

            SqlParameter[] param = new SqlParameter[]

            {

                new SqlParameter("@action",Objp.action),

                new SqlParameter("@customer_id",Objp.customer_id),

                new SqlParameter("@customer_name",Objp.customer_name),

                new SqlParameter("@address_text",Objp.address_text),

                new SqlParameter("@contact_no",Objp.contact_no),

                new SqlParameter("@email",Objp.email),

                new SqlParameter("@password",Objp.password)

            };

            dtt = objDL.ExecProc(ProcName, param);

            return dtt;

        }

 

        public DataTable AutoCompele(string ProcName)

        {

            DataTable dtt = new DataTable();

            SqlParameter[] param = new SqlParameter[]

            {

            };

            dtt = objDL.ExecProc(ProcName, param);

            return dtt;

        }

    }

}

Step #5

Create a Customer.cs Class in Models Folder by Right click on Models folder.

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Data;

 

namespace MyFirstApp.Models

{

    [Bind(Exclude = "action")]

    public class Customer

    {

        public int action { get; set; }

        public int customer_id { get; set; }

        [Required(ErrorMessage = "*")]

        public string customer_name { get; set; }

        [Required(ErrorMessage = "*")]

        public string address_text { get; set; }

        [Required(ErrorMessage = "*")]

        public string contact_no { get; set; }

        [Required(ErrorMessage = "*")]

        public string email { get; set; }

        [Required(ErrorMessage = "*")]

        public string password { get; set; }

        [ScaffoldColumn(false)]

        public DataTable customerDT { get; set; }

 

    }

}

Step #6

  • Create a HomeController Class in Controller Folder by Right click on Controller folder.
  • Add an action Name registration (See Below Image)

Create a HomeController



using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Globalization;

using System.Linq;

using System.Net;

using System.Net.Sockets;

using System.Web;

using System.Web.Mvc;

using MyFirstApp.Models;

 

namespace MyFirstApp.Controllers

{

    public class HomeController : Controller

    {

        MiddleLayer objML = new MiddleLayer();

        public ActionResult Index()

        {

            return View();

        }

        public ActionResult registration()

        {

            Customer objModel = new Customer();

            objModel.customerDT = GetRegistrationData(objModel);

            return View(objModel);

        }

        [HttpPost]

        public ActionResult registration(Customer model)

        {

 

            if (ModelState.IsValid)

            {

                DataTable dtt = new DataTable();

                model.action = model.customer_id > 0 ? 4 : 1; //Pass Action To Insert And Update Data

                dtt = objML.CustomerCRUD(model, "UserRegistration");

                if (dtt.Rows.Count > 0)

                {

                    if (Convert.ToInt32(dtt.Rows[0]["StatusCode"]) == 1)

                    {

                        ViewBag.StatusCode = dtt.Rows[0]["StatusCode"];

                        ViewBag.Msg = dtt.Rows[0]["Msg"];

 

                        //BindDataAfter DataSaved

                        ModelState.Clear();

                        model = new Customer();

                        model.customerDT = GetRegistrationData(model);

                    }

                }

                else

                {

                    ViewBag.Msg = "Something Went Wrong !";

                }

            }

            else

            {

                ViewBag.Msg = "Something Went Wrong !";

            }

            return View(model);

        }

 

        DataTable GetRegistrationData(Customer model)

        {

            model.action = 2; //Pass Action To Get Data

            return objML.CustomerCRUD(model, "UserRegistration");

        }

        public JsonResult edit_customer(int customer_id)

        {

            Customer model = new Customer();

            try

            {

                model.action = 3;

                model.customer_id = customer_id;

                DataTable dt = objML.CustomerCRUD(model, "UserRegistration");

                if (dt != null && dt.Rows.Count > 0)

                {

                    model.customer_id = Convert.ToInt32(dt.Rows[0]["customer_id"]);

                    model.customer_name = dt.Rows[0]["customer_name"].ToString();

                    model.address_text = dt.Rows[0]["address_text"].ToString();

                    model.contact_no = dt.Rows[0]["contact_no"].ToString();

                    model.email = dt.Rows[0]["email"].ToString();

                    model.password = dt.Rows[0]["password"].ToString();

                }

            }

            catch (Exception ex)

            {

            }

            return Json(model, JsonRequestBehavior.AllowGet);

        }

    }

}


Step #7

After Adding HomeController and action in it, Now Right-click on the registration action to add view. (See Below Image)

add razor view



@model MyFirstApp.Models.Customer

 

@{

    ViewBag.Title = "Registration";

}

@using System.Data    @*UserNameSpace To Access DataTable On RazorPage*@

<h2>CURD Operation In MVC</h2>

 

 

@using (Html.BeginForm())

{

    @Html.AntiForgeryToken()

 

    <div class="form-horizontal">

        <h4>Registration Form</h4>

        <hr />

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <div class="form-group">

            @Html.HiddenFor(m => m.customer_id, new { @id = "hdn_customer_id" })

            <label class="control-label col-md-2">Customer Name</label>

            <div class="col-md-10">

                @Html.EditorFor(model => model.customer_name, new { htmlAttributes = new { @class = "form-control", @id = "txt_customer_name" } })

                @Html.ValidationMessageFor(model => model.customer_name, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            <label class="control-label col-md-2">Address</label>

            <div class="col-md-10">

                @Html.EditorFor(model => model.address_text, new { htmlAttributes = new { @class = "form-control", @id = "txt_address_text" } })

                @Html.ValidationMessageFor(model => model.address_text, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            <label class="control-label col-md-2">Contact No</label>

            <div class="col-md-10">

                @Html.EditorFor(model => model.contact_no, new { htmlAttributes = new { @class = "form-control", @id = "txt_contact_no" } })

                @Html.ValidationMessageFor(model => model.contact_no, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            <label class="control-label col-md-2">Email Id</label>

            <div class="col-md-10">

                @Html.EditorFor(model => model.email, new { htmlAttributes = new { @class = "form-control", @id = "txt_email" } })

                @Html.ValidationMessageFor(model => model.email, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            <label class="control-label col-md-2">Password</label>

            <div class="col-md-10">

                @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control", @id = "txt_password" } })

                @Html.ValidationMessageFor(model => model.password, "", new { @class = "text-danger" })

            </div>

        </div>

 

        <div class="form-group">

            <div class="col-md-offset-2 col-md-10">

                <input type="submit" value="Create" id="btn_Save" class="btn btn-default" />

            </div>

        </div>

 

        <div class="form-group">

            <div class="col-md-offset-2 col-md-10">

                <label class="control-label col-md-2 vb_msg">

                    @ViewBag.Msg

                </label>

            </div>

        </div>

 

        <div class="row">

            <h4>Customer List</h4>

            <hr />

            <div class="col-lg-12">

                <table class="table table-bordered table-responsive">

                    <thead>

                        <tr>

                            <td>Customer ID</td>

                            <td>Customer Name</td>

                            <td>Address</td>

                            <td>Contact No</td>

                            <td>Email ID</td>

                            <td>Password</td>

                            <td>Action</td>

                        </tr>

                    </thead>

                    <tbody>

                        @if (Model.customerDT != null && Model.customerDT.Rows.Count > 0)

                        {

                            foreach (DataRow dr in Model.customerDT.Rows)

                            {

                                <tr>

                                    <td>@dr["customer_id"]</td>

                                    <td>@dr["customer_name"]</td>

                                    <td>@dr["address_text"]</td>

                                    <td>@dr["contact_no"]</td>

                                    <td>@dr["email"]</td>

                                    <td>@dr["password"]</td>

                                    <td>

                                        <a href="javascript:void(0)" onclick="edit('@dr["customer_id"]');">

                                            Edit

                                        </a>

                                    </td>

                                </tr>

                            }

                        }

                        else

                        {

                            <tr>

                                <td clospan="6">

                                    No Record Found !

                                </td>

                            </tr>

 

                        }

                    </tbody>

                </table>

            </div>

        </div>

    </div>

 

}

 

<script>

    function edit(customer_id) {

        var dataobject =

        {

            customer_id: customer_id

        };

        $.ajax({

            type: "POST",

            url: "/Home/edit_customer",

            data: dataobject,

            dataType: "json",

            success: function (r) {

                debugger;

                if (r != null) {

                    $("#hdn_customer_id").val(r.customer_id);

                    $("#txt_customer_name").val(r.customer_name);

                    $("#txt_address_text").val(r.address_text);

                    $("#txt_contact_no").val(r.contact_no);

                    $("#txt_email").val(r.email);

                    $("#txt_password").val(r.password);

                    $("#btn_Save").val('Update');

                    $(".vb_msg").text('');

                }

                else {

                    alert("Details Not Found !!!");

                }

            }

        });

    }

</script>

 

<div>

    @Html.ActionLink("Back to List", "Index")

</div>

 

@section Scripts {

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

}

 

Step #8

After Setting all the above things, Add the connection string in Web. config File

  <connectionStrings>

    <add name="MYCON" connectionString="Data Source=MSI;Initial Catalog=dotnet_tutorial;integrated security=true;" />

  </connectionStrings>


WebConfig Explanation

1.   <connectionStringsis a tag where we add a connection in it.

2.  name="MYCON" Add the connection string name to this key.

3.  Data Source Add your computer Name to this key.

4.  Initial Catalog Add Database Name to this key.

Step #9

Now press ctrl+f5 to run the application, you will see the below interface.

Step #10

Fill the Data and Check.

Finally, Record is inserted by the Asp.net MVC registration. If you get any problems. Please feel free to comment below.

Post a Comment

Post a Comment (0)

Previous Post Next Post