Introduction
This article explains how to insert data into a SQL Server database using jQuery using a post method in ASP.NET MVC 4.
Step 1: Create new project
Go to "File" -> "New" -> "Project..." then Select ASP.NET MVC4 web application then enter the Application Name then click OK then select Internet Application then select View Engine Razor then click OK.
Step 2: Add a database and create a table in it.
Go to Solution Explorer then right-click on the App_Data folder then click Add > New item then select SQL Server Database under Data then enter the database name then click Add.
- CREATE TABLE [dbo].[tblUserInfo] (
- [Id] INT IDENTITY (1, 1) NOT NULL,
- [UserName] VARCHAR (50) NULL,
- [UserContact] VARCHAR (50) NULL,
- PRIMARY KEY CLUSTERED ([Id] ASC)
- );
Step 3: Add entity data model
Go to Solution Explorer then right-click on the project name in the Solution Explorer then click Add > New item then select ADO.Net Entity Data Model under Data then enter the model name then click Add.
The Entity Data Model Wizard will open as a popup window then select Generate from database then click Next.
Choose your data connection then select your database then click Next then select Tables then enter the Model namespace then click Finish.
Step 4: Apply validation on model
Open your model and add validation.
- namespace MvcAppInsertUsingJquery
- {
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
-
- public partial class tblUserInfo
- {
- public int Id { get; set; }
- [Required(ErrorMessage = "Contact Name required!", AllowEmptyStrings = false)]
- public string UserName { get; set; }
- [Required(ErrorMessage = "Contact No required!", AllowEmptyStrings = false)]
- public string UserContact { get; set; }
- }
- }
Step 5: Add a new controller
Go to Solution Explorer then right-click on the Controllers folder in the Solution Explorer then click Add > Controller then enter the Controller name then select Templete "empty MVC Controller".
Step 6: Add a new action into your controller to insert the data. Here I added a "Save" Action into the "Ajax" Controller. Please write the following code:
- public ActionResult Save()
- {
- return View();
- }
Step 7: Add view for the action
Right-click on the Action Method then click Add View then enter View Name then select View Engine then check "Create a strong-typed view" then select your model class then click Add.
- @model MvcAppInsertUsingJquery.tblUserInfo
-
- @{
- ViewBag.Title = "Save";
- }
-
- <style>
- .success {
- border:solid 1px #0d6d00;
- width:300px;
- padding:5px;
- background-color:#d7ffda;
- }
- .failed {
- border:solid 1px red;
- width:300px;
- padding:5px;
- background-color:#ffe5e5;
- }
- </style>
-
- <h2 style="font-size:12pt; font-weight:bold;">Ajax Save - Contact Info</h2>
- @using (Html.BeginForm()) {
- @Html.ValidationSummary(true);
- <fieldset style="background-color:#ffffff">
- <legend>Contact Info</legend>
- <div style="padding:20px;">
- <div class="editor-label">
- Contact Name
- </div>
- <div class="editor-field">
- @Html.EditorFor(model => model.UserName)
- @Html.ValidationMessageFor(model => model.UserName)
- </div>
-
- <div class="editor-label">
- Contact No
- </div>
- <div class="editor-field">
- @Html.EditorFor(model => model.UserContact)
- @Html.ValidationMessageFor(model => model.UserContact)
- </div>
-
- <p>
- <input type="button" value="Save" id="AjaxPost"/>
- </p>
- <div id="content">
-
- </div>
- </div>
- </fieldset>
- }
- <div>
- @Html.ActionLink("Back to List", "Index")
- </div>
- @section Scripts{
- @Scripts.Render("~/bundles/jqueryval")
- <script>
- $(document).ready(function(){
- $("#AjaxPost").click(function(){
- $("#content").html("<b>Please Wait...</b>");
-
- var dataObject = {
- UserName: $("#UserName").val(),
- UserContact: $("#UserContact").val()
- };
- $.ajax({
- url: "@Url.Action("Save","InsertData")",
- type: "POST",
- data: dataObject,
- dataType: "json",
- success: function (data) {
- if (data.toString() == "Successfully Saved!") {
- $("#UserName").val(
- $("#UserContact").val(
- $("#content").html("<div class='success'>"+data+"</div>");
- }
- else {
- $("#content").html("<div class='failed'>" + data + "</div>");
- }
- },
- error: function () {
- $("#content").html("<div class='failed'>Error! Please try again</div>");
- }
- });
- })
- })
- </script>
- }
Step 8: Add another action into the controller for inserting the data into the server. Here I added a "Save" Action into the "Ajax" Controller for a POST Action.
- [HttpPost]
- public ActionResult Save(tblUserInfo userinfo)
- {
- string message = "";
- if(ModelState.IsValid)
- {
- try
- {
- using(AjaxInsertDBEntities aid=new AjaxInsertDBEntities())
- {
- aid.tblUserInfoes.Add(userinfo);
- aid.SaveChanges();
- message = "Successfully Saved!";
- }
- }
- catch (Exception ex) { message = "Error! Please try again."; }
- }
- else
- {
- message = "Please provide required fields value.";
- }
- if (Request.IsAjaxRequest())
- {
- return new JsonResult { Data = message, JsonRequestBehavior = RequestBehavior.AllowGet };
- }
- else
- {
- ViewBag.Message = message;
- return View(userinfo);
- }
- }
Step 9: Run the application.