0
\$\begingroup\$

I have created an Application on MVC which makes Select, Insert, Update and Delete on a single page and I need to make it optimised.

I have created 2 partial pages, one for grid and another to submit data and I had called those partial pages into a single View.

Index.cshtml page layout:

@model WebApplication1.Models.Employee
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<!DOCTYPE html>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
<html>
<head>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="//cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/build/css/bootstrap-datetimepicker.css" />
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    <div class="register_form full_width_reg">
        @using (Html.BeginForm("Insertdata", "Employee", FormMethod.Get, new { @class = "form-horizontal", @id = "insertform", role = "form", enctype = "multipart/form-data" }))
        {
            <div id="addupdate"></div>
        }
    </div>
    <div id="grid">
    </div>
</body>
</html>
@*<script src="https://code.jquery.com/jquery-3.3.1.js"></script>*@
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/Eonasdan/bootstrap-datetimepicker/e8bddc60e73c1ec2475f827be36e1957af72e2ea/src/js/bootstrap-datetimepicker.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "/Employee/GetAddUpdate",
            contentType: "application/json; charset=utf-8",
            dataType: "html",
            success: function (response) {
                if (response != null) {
                    $("#addupdate").html(response);
                    $('#datetimepicker1').datetimepicker();
                    $.validator.unobtrusive.parse("#insertform");
                } else {
                    alert("Something went wrong");
                }
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
        bindgrid();
    });

    function bindgrid() {
        $.ajax({
            type: "GET",
            url: "/Employee/Getpartialdata",
            contentType: "application/json; charset=utf-8",
            dataType: "html",
            success: function (response) {
                if (response != null) {
                    $("#grid").html(response);                    

                    $('#example').DataTable({
                        "order": [[0, "desc"]]
                    });

                } else {
                    alert("Something went wrong");
                }
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
    }

    function insert() {
        if ($("#txtname").val() == '' || $("#txtemail").val() == '' || $("#datetimepicker7").val() == '' || $("#designationid").val() == ''
            || $("#txtsalary").val() == '' || $("#designationid").val() == '') {
            $("#validate").click();
            return false;
        }
        $.ajax({
            type: "GET",
            url: "/Employee/Insertdata",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: $("#insertform").serialize(),
            success: function (response) {
                bindgrid();
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
    }
</script>

_AddUpdateData.cshtml is my partial page from where I used to Add and Update the data:

@model WebApplication1.Models.Employee
@Html.HiddenFor(m => m.empid)
@Html.ValidationSummary(true)
<h3>Register as a Student</h3>
<hr />
<div class="hidden"></div>

<div class="form-group col-md-6 col-sm-6">
    <div class="row">
        <label class="col-md-4 control-label" for="Name">Name</label>
        <div class="col-md-8">
            @Html.EditorFor(model => model.empname, new { htmlAttributes = new { @class = "form-control", id = "txtname", placeholder = "Name" } })
            @Html.ValidationMessageFor(model => model.empname)
        </div>
    </div>
</div>
<div class="form-group col-md-6 col-sm-6">
    <div class="row">
        <label class="col-md-4 control-label" for="Campus">Designation</label>
        <div class="col-md-8">
            @Html.DropDownListFor(model => model.designationid, Model.AvailableDesig, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.designationid)
        </div>
    </div>
</div>
<div class="clearfix"></div>
<div class="form-group col-md-6 col-sm-6">
    <div class="row">
        <label class="col-md-4 control-label" for="Phone">Email Address</label>
        <div class="col-md-8">
            @Html.EditorFor(model => model.empemail, new { htmlAttributes = new { @class = "form-control", id = "txtemail", placeholder = "Email Address" } })
            @Html.ValidationMessageFor(model => model.empemail)
        </div>
    </div>
</div>
<div class="form-group col-md-6 col-sm-6">
    <div class="row">
        @Html.LabelFor(m => m.empsalary, new { @class = "col-md-4 control-label" })
        <div class="col-md-8">
            @Html.EditorFor(model => model.empsalary, new { htmlAttributes = new { @class = "form-control", id = "txtsalary", placeholder = "Salary" } })
            @Html.ValidationMessageFor(model => model.empsalary)

        </div>
    </div>
</div>
<div class="clearfix"></div>

<div class="form-group col-md-6 col-sm-6">
    <div class="row">
        @Html.LabelFor(m => m.date, new { @class = "col-md-4 control-label" })
        <div class="col-md-8">
            @Html.EditorFor(m => m.date, new { htmlAttributes = new { @class = "form-control input-group date", id = "datetimepicker1", placeholder = "Date" } })
            @Html.ValidationMessageFor(model => model.date)
        </div>
    </div>
</div>

<div class="form-group col-md-6 col-sm-6">
    <div class="row">
        @Html.LabelFor(m => m.gender, new { @class = "col-md-4 control-label" })
        <div class="col-md-8">
            @Html.Label("Male")
            @Html.RadioButtonFor(m => m.gender, "Male")
            @Html.Label("Female")
            @Html.RadioButtonFor(m => m.gender, "Female")
            @Html.ValidationMessageFor(model => model.gender)
        </div>
    </div>
</div>
<div class="form-group col-md-6 col-sm-6">
    <div class="row">
        <div class="col-md-offset-4 col-md-10">
            <input type="submit" id="validate" class="btn btn-default btn-browse" value="Add" style="display:none;" />
            <input type="button" id="submitfilteration" onclick="return insert();" class="btn btn-default btn-browse" value="Add" />
        </div>
    </div>
</div> 

_PartialGrid.cshtml is my another Partial View where we can show all added data:

@model IList<WebApplication1.Models.Employee>

    <table id="example" class="table table-striped table-bordered" style="width:100%">
        <thead>
            <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Email</th>
                <th>Gender</th>
                <th>Designation</th>
                <th>Salary</th>
                <th>Date</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {

            <tr>
                <td>@item.empid</td>
                <td>@item.empname</td>
                <td>@item.empemail</td>
                <td>@item.gender</td>
                <td>@item.name</td>
                <td>@item.empsalary</td>
                <td>@item.date</td>
                <td>
                    <input type="button" id="Editbtn" onclick="Editdata('@item.empid')" class="btn btn-default btn-browse" value="Edit" />
                </td>
                <td>
                    <input type="button" id="deletebutton" onclick="Delete('@item.empid');" class="btn btn-default btn-browse" value="Delete" />
                </td>
            </tr>
            }           
        </tbody>
    </table>
<script>
    function Delete(id) {      
        $.ajax({
            url: '/Employee/Delete',
            dataType: "html",
            type: "POST", // You can use GET
            contentType: 'application/json; charset=utf-8',
            cache: false,
            data: JSON.stringify({
                'id': id
            }),
            success: function (data) {               
                bindgrid();

            },
            error: function (xhr) {
                console.log(request);               
            }
        });
    }
    function Editdata(id) {
        $.ajax({
            url: '/Employee/Edit',
            dataType: "html",
            type: "POST", // You can use GET
            contentType: 'application/json; charset=utf-8',
            cache: false,
            data: JSON.stringify({
                'id': id
            }),
            success: function (data) {
                $("#addupdate").html(data);
                $.validator.unobtrusive.parse("#insertform");               
                alert('success');
            },
            error: function (xhr) {
                console.log(request);
                // alert("Some error");
            }
        });
    }
    function bindgrid() {
        $.ajax({
            type: "GET",
            url: "/Employee/Getpartialdata",
            contentType: "application/json; charset=utf-8",
            dataType: "html",
            success: function (response) {
                if (response != null) {
                    $("#grid").html(response);
                    $('#example').DataTable();
                } else {
                    alert("Something went wrong");
                }
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
    }
</script>

EmployeeController.cs is my controller:

namespace WebApplication1.Controllers
{

    public class EmployeeController : Controller
    {
        PracmvcEntities db = new PracmvcEntities();       
        public ActionResult Index()
        {
            Employee emp = new Employee();
            emp.AvailableDesig = GetDesig();
            return View(emp);
        }              
        [HttpGet]
        public ActionResult Insertdata(Employee model)
        {
            bool gender = false;
            if (model.empid == null)
            {                
                if (model.gender == "Male")
                {
                    gender = true;
                }
                db.insertemployeedata(model.empname, gender, model.designationid, model.empemail, model.empsalary, model.date);
                db.SaveChanges();
                return Json("success", JsonRequestBehavior.AllowGet);
            }
            //edit           
            if (model.gender == "Male")
            {
                gender = true;
            }
            db.updateemployeedata(model.empid,model.empname, gender, model.designationid, model.empemail, model.empsalary, model.date);
            db.SaveChanges();
            return Json("success", JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult GetAddUpdate()
        {
            Employee emp = new Employee();
            emp.AvailableDesig = GetDesig();
            return PartialView("_AddUpdateData", emp);
        }
        [HttpGet]
        public ActionResult Getpartialdata()
        {
            List<Employee> emp = db.selectemployeedata(0).Select(e => new Employee
            {
                empid = e.empid,
                empname = e.empname,
                empsalary = Convert.ToDecimal(e.empsalary),
                empemail = e.empemail,
                gender = e.gender.ToString(),
                name = db.designations.Where(a => a.id == e.designationid).FirstOrDefault().name,
                id=e.id,
                date=e.date
            }).ToList();
            return PartialView("_PartialGrid", emp);
        }
        public IList<SelectListItem> GetDesig()
        {
            // This comes from database.       
            var desig = db.selectemployeeedesignation()
                .Select(x => new SelectListItem { Text = x.name, Value = x.id.ToString() })
                .ToList();
            desig.Insert(0, new SelectListItem { Text = "--Please Select--", Value = "" });
            return desig;
        }
        [HttpPost]
        public ActionResult Edit(int id)
        {
            Employee emp = db.selectemployeedata(id).Select(e => new Employee
            {
                empid = e.empid,
                empname = e.empname,
                empsalary = Convert.ToDecimal(e.empsalary),
                empemail = e.empemail,
                gender = e.gender.ToString()=="True"? "Male" : "Female",
                name = db.designations.Where(a => a.id == e.designationid).FirstOrDefault().name,
                id = e.id,
                date = e.date,
                designationid=e.designationid                                
            }).FirstOrDefault();                        
            emp.AvailableDesig = GetDesig();
            return PartialView("_AddUpdateData", emp);            
        }
        [HttpPost]
        public ActionResult Delete(int id)
        {
            db.deleteemployee(id);
            db.SaveChanges();
            // This comes from database.       
            return Json("success", JsonRequestBehavior.AllowGet);
        }
    }
}

Employee.cs is my model:

namespace WebApplication1.Models
{
    public class Employee
    {
        public Employee()
        {
            AvailableDesig = new List<SelectListItem>();
        }
        public int? empid { get; set; }
        [Required(ErrorMessage = "Name Required.")]
        public string empname { get; set; }
        [Required(ErrorMessage = "Gender Required.")]
        public string gender { get; set; }
        [Required(ErrorMessage = "Please Select {0}.")]
        public Nullable<int> designationid { get; set; }
        [Required(ErrorMessage = "Email Address Required.")]
        public string empemail { get; set; }
        [Required(ErrorMessage = "Salary Required.")]
        public Nullable<System.Decimal> empsalary { get; set; }
        [Required(ErrorMessage = "Date Required.")]
        public Nullable<System.DateTime> date { get; set; }
        public int id { get; set; }
        public string name { get; set; }
        public IList<SelectListItem> AvailableDesig { get; set; }
        public IList<Employeedesignation> desig { get; set; }
    }
    public class Employeedesignation
    {
        public int id { get; set; }
        public string name { get; set; }
    }
}

I am also giving you the script to generate the database:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[designation](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](250) NULL,
 CONSTRAINT [PK_designation] PRIMARY KEY CLUSTERED 
(
    [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
/****** Object:  Table [dbo].[employee]    Script Date: 1/15/2019 10:32:42 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[employee](
    [empid] [int] IDENTITY(1,1) NOT NULL,
    [empname] [varchar](250) NULL,
    [gender] [bit] NULL,
    [designationid] [int] NULL,
    [empemail] [varchar](250) NULL,
    [empsalary] [varchar](250) NULL,
    [date] [datetime] 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
/****** Object:  StoredProcedure [dbo].[deleteemployee]    Script Date: 1/15/2019 10:32:42 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[deleteemployee]
    @empid int
AS
BEGIN
    SET NOCOUNT ON;
    delete from employee where empid=@empid
END

GO
/****** Object:  StoredProcedure [dbo].[insertemployeedata]    Script Date: 1/15/2019 10:32:42 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[insertemployeedata]
    @empname varchar(250)=null,
    @gender bit,
    @designationid int=null,
    @empemail varchar(250)=null,
    @empsalary decimal(8,2)=null,
    @date datetime
as
BEGIN
    SET NOCOUNT ON;
    insert into employee values(@empname,@gender,@designationid,@empemail,@empsalary,@date)

END

GO
/****** Object:  StoredProcedure [dbo].[selectemployeedata]    Script Date: 1/15/2019 10:32:42 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[selectemployeedata]
@empid int=0
AS
BEGIN
    SET NOCOUNT ON;
    if(@empid=0)
    begin
    select * from employee e inner join designation d on e.designationid=d.id 
    end
    else if (@empid>0)
    begin
    select * from employee e inner join designation d on e.designationid=d.id where e.empid=@empid 
    end
END

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[selectemployeeedesignation]

AS
BEGIN   
    SET NOCOUNT ON;
select * from designation
END

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[updateemployeedata]
@empid int,
        @empname varchar(250)=null,
    @gender bit,
    @designationid int=null,
    @empemail varchar(250)=null,
    @empsalary decimal(8,2)=null,
    @date datetime
AS
BEGIN
    SET NOCOUNT ON;
    update employee set empname=@empname, gender=@gender, designationid=@designationid,empemail=@empemail,empsalary=@empsalary,[date]=@date where empid=@empid
END

GO

In my case the insertion and updating is taking time. Can anyone help me to optimize my code?

\$\endgroup\$
  • 3
    \$\begingroup\$ Could you add a few sentences to explain the purpose of the application? What data is does it work with? What benefit does it provide the user? etc. Thanks. \$\endgroup\$ – Toby Speight Jan 15 at 18:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.