Monday, November 28, 2016

Part 14 - Insert data into database using jQuery AJAX in Asp.net MVC application





#Controller Code

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

namespace MVCTutorial.Controllers
{
    public class TestController : Controller
    {

        public ActionResult Index()
        {
            MVCTutorialEntities db = new MVCTutorialEntities();

            List<Department> list = db.Departments.ToList();
            ViewBag.DepartmentList = new SelectList(list, "DepartmentId", "DepartmentName");

            return View();
        }


        [HttpPost]
        public ActionResult Index(EmployeeViewModel model)
        {
            try
            {

                MVCTutorialEntities db = new MVCTutorialEntities();
                List<Department> list = db.Departments.ToList();
                ViewBag.DepartmentList = new SelectList(list, "DepartmentId", "DepartmentName");

                Employee emp = new Employee();
                emp.Address = model.Address;
                emp.Name = model.Name;
                emp.DepartmentId = model.DepartmentId;

                db.Employees.Add(emp);
                db.SaveChanges();

                int latestEmpId = emp.EmployeeId;


                Site site = new Site();
                site.SiteName = model.SiteName;
                site.EmployeeId = latestEmpId;

                db.Sites.Add(site);
                db.SaveChanges();
            }
            catch (Exception ex)
            {

                throw ex;
            }

            return View(model);
        }


    }
}
  
#Model code (EmployeeViewModel)


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

namespace MVCTutorial.Models
{
    public class EmployeeViewModel
    {
        public int EmployeeId { get; set; }

        [Required(ErrorMessage = "Enter Name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Enter Department")]
        public Nullable<int> DepartmentId { get; set; }

        [Required(ErrorMessage = "Enter Address")]
        public string Address { get; set; }

        //Custom attribute
        public string DepartmentName { get; set; }
        public bool Remember { get; set; }
        public string SiteName { get; set; }
       
    }
}

 # View Page (Index.cshtml)


@model MVCTutorial.Models.EmployeeViewModel
@{
    ViewBag.Title = "Index";
    Layout = null;
}

<link href="~/Content/bootstrap.min.css" rel="stylesheet" />



<div class="container" style="width:40%;margin-top:2%">

    <form id="myForm">

        @Html.DropDownListFor(model => model.DepartmentId, ViewBag.DepartmentList as SelectList, "--select--", new { @class = "form-control" })

        @Html.TextBoxFor(model => model.Name, new { @class = "form-control", @placeholder = "Name" })

        @Html.TextBoxFor(model => model.Address, new { @class = "form-control", @placeholder = "Address" })

        @Html.TextBoxFor(model => model.SiteName, new { @class = "form-control", @placeholder = "SiteName" })

        <input type="reset" value="Submit" class="btn btn-block btn-primary" id="btnSubmit" />

    </form>

    <div style="text-align:center;display:none" id="loaderDiv">
        <img src="~/Content/InternetSlowdown_Day.gif" width="150" />
    </div>
</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(document).ready(function () {

        $("#btnSubmit").click(function () {
            debugger
            $("#loaderDiv").show();

            var data = $("#myForm").serialize();

            $.ajax({

                type: "POST",
                url: "/Test/Index",
                data: data,
                success: function (response) {
                    $("#loaderDiv").hide();
                    alert("you are done");
                }

            })
        })


    })


</script>

<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>


#Database Script


USE [MVCTutorial]
GO
/****** Object:  Table [dbo].[Department]    Script Date: 27-11-2016 00:28:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Department](
 [DepartmentId] [int] IDENTITY(1,1) NOT NULL,
 [DepartmentName] [nvarchar](100) NULL,
 CONSTRAINT [PK_Department] PRIMARY KEY CLUSTERED 
(
 [DepartmentId] 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
/****** Object:  Table [dbo].[Employee]    Script Date: 27-11-2016 00:28:18 ******/
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,
 [Name] [varchar](50) NULL,
 [DepartmentId] [int] NULL,
 [Address] [varchar](150) 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
/****** Object:  Table [dbo].[Sites]    Script Date: 27-11-2016 00:28:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Sites](
 [SiteId] [int] IDENTITY(1,1) NOT NULL,
 [EmployeeId] [int] NULL,
 [SiteName] [nvarchar](150) NULL,
 CONSTRAINT [PK_Sites] PRIMARY KEY CLUSTERED 
(
 [SiteId] 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 IDENTITY_INSERT [dbo].[Department] ON 

GO
INSERT [dbo].[Department] ([DepartmentId], [DepartmentName]) VALUES (1, N'IT')
GO
INSERT [dbo].[Department] ([DepartmentId], [DepartmentName]) VALUES (2, N'QA')
GO
INSERT [dbo].[Department] ([DepartmentId], [DepartmentName]) VALUES (3, N'Development ')
GO
INSERT [dbo].[Department] ([DepartmentId], [DepartmentName]) VALUES (4, N'Marketing')
GO
SET IDENTITY_INSERT [dbo].[Department] OFF
GO
SET IDENTITY_INSERT [dbo].[Employee] ON 

GO
INSERT [dbo].[Employee] ([EmployeeId], [Name], [DepartmentId], [Address]) VALUES (1, N'Ashish', 1, N'India')
GO
INSERT [dbo].[Employee] ([EmployeeId], [Name], [DepartmentId], [Address]) VALUES (2, N'John', 2, N'London')
GO
INSERT [dbo].[Employee] ([EmployeeId], [Name], [DepartmentId], [Address]) VALUES (3, N'Methew', 3, N'NewYork')
GO
INSERT [dbo].[Employee] ([EmployeeId], [Name], [DepartmentId], [Address]) VALUES (4, N'Brano', 4, N'France')
GO
INSERT [dbo].[Employee] ([EmployeeId], [Name], [DepartmentId], [Address]) VALUES (5, N'Smith', 1, N'London')
GO
INSERT [dbo].[Employee] ([EmployeeId], [Name], [DepartmentId], [Address]) VALUES (6, N'Sara', 4, N'New york')
GO
SET IDENTITY_INSERT [dbo].[Employee] OFF
GO
SET IDENTITY_INSERT [dbo].[Sites] ON 

GO
INSERT [dbo].[Sites] ([SiteId], [EmployeeId], [SiteName]) VALUES (1, 1005, N'google.com')
GO
INSERT [dbo].[Sites] ([SiteId], [EmployeeId], [SiteName]) VALUES (2, 1006, N'www.technotips.com')
GO
SET IDENTITY_INSERT [dbo].[Sites] OFF
GO
ALTER TABLE [dbo].[Employee]  WITH CHECK ADD  CONSTRAINT [FK_Employee_Department] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Department] ([DepartmentId])
GO
ALTER TABLE [dbo].[Employee] CHECK CONSTRAINT [FK_Employee_Department]
GO
ALTER TABLE [dbo].[Sites]  WITH CHECK ADD  CONSTRAINT [FK_Sites_Employee] FOREIGN KEY([EmployeeId])
REFERENCES [dbo].[Employee] ([EmployeeId])
GO
ALTER TABLE [dbo].[Sites] CHECK CONSTRAINT [FK_Sites_Employee]
GO
   


All Code Factory

53 comments:

Unknown said...

If you can provide project also. It will be quite useful.

rmouniak said...

Wow its an amazing blog
.Net Online Training Bangalore

Tejuteju said...

Nice Information Keep Learning Ruby on Rails Online Course

sai said...

I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
python training in chennai
python course in chennai

Unknown said...

Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.

rpa training in bangalore
best rpa training in bangalore
RPA training in bangalore
rpa courses in bangalore

haripriya said...

Wonderful bloggers like yourself who would positively reply encouraged me to be more open and engaging in commenting.So know it's helpful.
Data Science training in Chennai
Data science training in Bangalore
Data science training in pune
Data science online training
Data Science Interview questions and answers
Data Science Tutorial



Unknown said...

I have visited this blog first time and i got a lot of informative data from here which is quiet helpful for me indeed. 
Python Online certification training
python Training institute in Chennai
Python training institute in Bangalore

rohini said...

That was a great message in my carrier, and It's wonderful commands like mind relaxes with understand words of knowledge by information's.
AWS Training in Bangalore

riya said...

I found this informative and interesting blog so i think so its very useful and knowledge able.I would like to thank you for the efforts you have made in writing this article.

Data Science course in Chennai
Data science course in bangalore
Data science course in pune
Data science online course
Data Science Interview questions and answers
Data Science Tutorial
Data science course in bangalore

zaintech99 said...

It should be noted that whilst ordering papers for sale at paper writing service, you can get unkind attitude. In case you feel that the bureau is trying to cheat you, don't buy term paper from it.
data analytics certification courses in Bangalore
ExcelR Data science courses in Bangalore

istiaq ahmed said...

I have a mission that I’m just now working on, and I have been at the look out for such information
Data Science Course in Pune

janitha said...

I recently found many useful information in your website especially this blog page. Among the lots of comments on your articles. Thanks for sharing.
data science course malaysia

data science analytics rakshi said...

I was just browsing through the internet looking for some information and came across your blog. I am impressed by the information that you have on this blog. It shows how well you understand this subject. Bookmarked this page, will come back for more.
data science course in singapore

lucy88 said...



Its as if you had a great grasp on the subject matter, but you forgot to include your readers. Perhaps you should think about this from more than one angle.
Data Science Courses

jaanu said...

I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.
big data course

Anonymous said...

Very awesome!!! When I seek for this pmp training I found this website at the top of all blogs in search engine.

Anonymous said...

I love the way you write Business Analytics Online Course and share your niche! Very interesting and different! Keep it coming!

Priyanka said...

Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. I appreciate your post and look forward to more.
ExcelR Data Analytics Course
Data Science Interview Questions

Excelrsolutions said...

This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.… data science courses

dataexpert said...

I have a mission that I’m just now working on, and I have been at the look out for such information ExcelR Best Data Science Courses In Pune

hami said...

click here formore info.

Keerthana said...

The Blogs are very Impressive, It is very helpful to all and I am wishing for all your Efforts Looking towards more

python training in chennai | python training in annanagar | python training in omr | python training in porur | python training in tambaram | python training in velachery

devi said...

I would really like to read some personal experiences like the way, you've explained through the above article. I'm glad for your achievements and would probably like to see much more in the near future. Thanks for share.Data Science Training In Chennai

Data Science Online Training In Chennai

Data Science Training In Bangalore

Data Science Training In Hyderabad

Data Science Training In Coimbatore

Data Science Training

Data Science Online Training

EXCELR said...

Attend The Data Science Courses From ExcelR. Practical Data Science Courses Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Science Courses. data science courses

EXCELR said...

Thanks for sharing this post, it was great reading this article! would like to know more! keep in touch and stay connecteddata scientist courses

EXCELR said...

I am looking for and I love to post a comment that "The content of your post is awesome" Great work! data science courses

hrithiksai said...

This Was An Amazing ! I Haven't Seen This Type of Blog Ever ! Thankyou For Sharing, data science online course

data scientist course said...

It's late finding this act. At least, it's a thing to be familiar with that there are such events exist. I agree with your Blog and I will be back to inspect it more in the future so please keep up your act.
data scientist course in hyderabad

3RI Technologies said...


Thanks for the tutorial on.net MVC, a really helpful blog. Keep writing and sharing.

Data Science Training in Pune

traininginstitute said...

I would like to say that this blog really convinced me to do it! Thanks, very good post.
data scientist course

Data Science said...

Amazingly by and large very interesting post. I was looking for such an information and thoroughly enjoyed examining this one. Keep posting. An obligation of appreciation is all together for sharing.data science training in kolhapur

Ramesh Sampangi said...

Informative blog, nice content. Thanks for writing this blog.
Data Scientist Training in Hyderabad
Data Scientist Training and Placements in Hyderabad

Data Science said...

Amazingly by and large very interesting post. I was looking for such an information and thoroughly enjoyed examining this one.
Keep posting. An obligation of appreciation is all together for sharing.
data science training in gwalior


traininginstitute said...

Great Information sharing .. I am very happy to read this article .. thanks for giving us go through info.Fantastic nice. I appreciate this post.
full stack developer course with placement

data science course in gorakhpur said...

Our Data Science certification training with a unique curriculum and methodology helps you to get placed in top-notch companies.

Data science course said...

It has lessened the load on the people as it works on the data patterns that minimize the data volumedata science course in ghaziabad.

Ashvin Kumar said...

The code you've supplied exemplifies a thorough MVC architecture for managing employee data. A model and view are used by the controller to handle personnel records effectively. The dynamic functionality is increased by the AJAX submission. The script further exemplifies effective database architecture. Well done!
Data Analytics Courses in India

Gayatri said...


This post provides a clear and comprehensive guide to inserting data into a database using jQuery AJAX in an ASP.NET MVC application. The well-structured code snippets and explanations make it easy to understand and implement. Great job!
Data Analytics Courses in Nashik

Divya Sharma said...

This article provides a comprehensive guide on inserting data into a database using jQuery AJAX in an ASP.NET MVC application. The code examples and explanations are very helpful. Thank you for sharing.
Is iim skills fake?

Data Analytics Courses in Agra said...

Hello! I simply want to give a huge thumbs up for the excellent information you have right here on this site. I'll probably be checking back soon for more on your blog!
Data Analytics Courses in Agra

Chase Lodge Hospital said...

This article furnishes a thorough guide on inserting data into a database using jQuery AJAX in an ASP.NET MVC application. The provided code examples and explanations are exceedingly helpful. Thank you for sharing.

Pratyaksha said...

This knowledge is immensely valuable for developers looking to create responsive and dynamic web applications.
Data Analytics Courses In Chennai

John Albert said...

Incredibly captivating centers you have noted , appreciation for setting up. Rick Grimes Jacket

DMC in Italy said...

I found this tutorial very informative on how to Insert data into database using jQuery AJAX in Asp.net MVC application. Thankyou for providing comprehensive tutorial.
Digital Marketing Courses in Italy

Ben said...

Helpful tutorial on inserting data into a database using PHP and MySQL. Your step-by-step instructions are beneficial for beginners. Thanks for sharing! Digital Marketing Courses In Hobart

Adwords said...

Thank you for sharing in depth knowledge and excelent tutorial on how to Insert data into database using jQuery AJAX in Asp.net MVC application.
Adwords marketing

sayaniimskillseo said...

such an interesting blog post, very well written & explained
Digital marketing business

Aishwarya said...

The blog post provides great tutorial on how to Insert data into database using jQuery AJAX in Asp.net MVC application.
Investment banking training Programs

Investment Banking Industry said...

Fantastic tutorial series! Clear explanations and well-organized code. Thanks for sharing the insights into database operations using jQuery in MVC.

Investment Banking Industry

nandni said...

Investor banker manager profile
Very interesting to read this article

Altar Runner said...

Your dedication to delivering quality content shines through.
Investment banking skills and responsibilities

Rajsingh said...

You explained step-by-step instructions, code snippets, and best practices for implementing this data insertion process. Useful for developers looking to enhance user experience and interactivity in their ASP.NET MVC applications. useful article.
Data analytics framework

Gogou Misao said...

Thanks for this really useful article. This was just what I needed to complete my PHP assignment.
Investment banking analyst jobs