How to insert data into a database using jQuery / Ajax in ASP.NET MVC?

save (insert) data from html table to database using jquery ajax in asp.net mvc
submit form using jquery ajax in asp.net mvc
update data into database using jquery ajax in asp net mvc
how to get data from database using jquery ajax in asp net mvc
asp mvc save multiple data jquery
how to insert data in database using jquery
how to make ajax call in mvc using jquery
how to save data in database on button click in mvc

I have been stuck for hours trying to find the bugs when trying to insert data into database using ajax. When I click submit button, it just reloads but does not save. I am confused about this problem. I have searched many blogs but did not find accurate solution to this problem.

Model class

public class Semester
{       
    [Key]
    public int SemesterId { get; set; }

    [Display(Name = "Semester Code")]
    [Required(ErrorMessage = "please enter semester code")]
    public string SemesterCode { get; set; }

    [Display(Name = "Semester Name")]
    [Required(ErrorMessage = "Please enter semeter name")]
    public string SemesterName { get; set; }
}

Controller [HttpGet]

  public ActionResult SaveSemesterGet()
  {
    return View();
   }
   public JsonResult AsCreateSemester(Semester semester){


            db.Semesters.Add(semester);
            db.SaveChanges();


        return Json(semester, JsonRequestBehavior.AllowGet);
     }

Index view:

      @model CampusManagementApp.Models.Semester
      <h2>SaveSemesterGet</h2>
      <form method="POST">

      @Html.AntiForgeryToken()

      <div >
        <h4>Semester</h4>
        @Html.ValidationSummary(true)

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

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

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" id="btn" value="SAVE"/>
        </div>
    </div>
 </div>

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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script>
    $(document).ready(function() {
           $("#btn").click(function(a) {

        a.preventDefault();
        var code = $("#SemesterCode").val();
        var name = $("#SemesterName").val();
        var jsonData = {
            SemesterCode: code,
            SemesterName: name
        };


        $.ajax({
            type: "POST",
            url: '@Url.Action("AsCreateSemester", "Semester")',
             data:  JSON.stringify(jsonData),
               dataType:"json",


            success:function(data) {
                alert(data.SemesterName+"successfully inserted");
            },

            failure: function () {
                alert("not successfull");
            }

        });
</script>

What can be done to get rid of this problem?

Why are you using a submit button? Since the JS function you made is handling the post, you don't need to use a submit button, which is causing the entire page to reload. Just use a normal button.

            <input type="button" id="btn" value="SAVE"/>

Insert Data Into Database Using jQuery Ajax POST Method in ASP , How can we get data from database using jQuery Ajax in ASP NET MVC? I have been stuck for hours trying to find the bugs when trying to insert data into database using ajax. When I click submit button, it just reloads but does not save. I am confused about this problem. I have searched many blogs but did not find accurate solution to this problem. Model class

You have several issues in the view:

1) You're subscribed to click event of a submit button without preventing default action which submitting the form. This triggered POST action which redirect away into the controller action and reload the page without leaving any time for AJAX function to execute. You should use preventDefault() to cancel the default action of the button.

2) The controller which receives AJAX callback does not have [HttpPost] attribute while type: "POST" option is used. Consider adding [HttpPost] attribute on top of controller name.

3) Your AJAX property names list does not match with property names defined inside model class. Consider using a viewmodel which accepts two properties and use it as action parameter.

Therefore, the AJAX callback should have setup as in example below:

Viewmodel

public class SemesterVM
{
    public string SemesterCode { get; set; }
    public string SemesterName { get; set; }
}

View

<input type="button" id="btn" value="SAVE" />

JS (click event)

$('#btn').click(function (e) {
    e.preventDefault(); // prevent default submit

    var code = $("#SemesterCode").val();
    var name = $("#SemesterName").val();

    // all property names must be same as the viewmodel has
    var jsonData = {
        SemesterCode: code,
        SemesterName: name
    };

    $.ajax({
        type: "POST",
        url: '@Url.Action("SaveSemester", "Student")',
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        dataType: "json",
        success: function() {
            // do something
        }
    });
});

Controller Action

[HttpPost]
public JsonResult SaveSemester(SemesterVM semester)
{
    // add semester data

    return Json(semester);
}

How to insert data into a database using jQuery / Ajax in ASP.NET , How can insert data in database in ASP NET MVC? Part 11 - Insert data Into database in as Asp.net MVC application Part 15 - How to create a bootstrap popup (bootstrap modal) and insert data using JQuery in ASP.NET MVC Part 33 - Upload and display image using JQuery in Asp.net MVC | To File server

After changing the ajax() method like below it works.

       $.ajax({
            type: "POST",
            url: '@Url.Action("AsCreateSemester", "Semester")',

         data: {
             SemesterCode: code,
             SemesterName: name
         },



            success:function(data) {
                alert(data.SemesterName+"successfully inserted");
            },

            failure: function () {
                alert("not successfull");
            }

        });

Part 14- Insert data into database using jQuery AJAX in ASP.NET , You have several issues in the view: 1) You're subscribed to click event of a submit button without preventing default action which submitting  Note that all functionality works without any page refresh as we are working with ajax and it works with the help of jQuery that is why we need to reference the jquery.unobtrusive-ajax.min.js file into the page.

How to Insert Data into Database in Asp.net MVC using Jquery Ajax , jquery ajax tutorial viewbag $controller $model razor view engine. Part 14 - Insert data into Duration: 18:51 Posted: Nov 28, 2016 In this article I will explain how to insert or update data asynchronously (without PostBack) to database using jQuery AJAX and Page Methods (WebMethod on Page) in ASP.Net. Database Schema I have created a new database named UsersDB which consist of one table named Users with the following schema.

WEB API Insert Data Using jQuery Ajax POST Method webform , Here I will explain How to Insert Data into Database in Asp.net MVC using Jquery Ajax. I Duration: 17:00 Posted: Aug 28, 2017 Now fill in the record in the TextBox and click the Save button to save the record to the database. Figure 4: Save Data Check in your database for the last inserted record as in the following: Figure 5: Check Record in Database Finally now you understand how to insert a record with jQuery ajax.

How to insert data into sql server databse using jquery (post method , webapipost #jqueryajaxinsert Consume web api into jquery to inserting data to database in Duration: 22:25 Posted: Oct 21, 2019 In this article I provide a quick overview of how to insert a record into SQL Server using jQuery. You can do it in many ways such as using Generic Handlers and using a WCF service. Here you will see it using jQuery with Ajax in ASP.Net.

Comments
  • Add the attribute HttpPost to the action you are using to post data.
  • You are executing the ajax call onload of window which happens before a user has a chance to interact with the page. Move that javascript to a function that you can call when the button is clicked.
  • not clear about your commnet ,what can be done @crowcoder
  • Disregard, I missed the part where you wired the click event. Did you try dougF's answer?
  • with regards,it dougF's answer does not work
  • chanded the input type but it doees not respond and save the data.
  • When you debug, is the JS being fired at all?
  • @Talukder if the JS isn't being fired when you debug, you might also have to change how you wired up the button. Instead of $("#btn").click(function() { maybe use $("#btn").on("click", function() { just in case for some reason the jquery isn't finding the button on page load.
  • Being updated code as above it saves null value in the database.
  • Using ModelState.IsValid doesn't make sense in AJAX callback. Also you're not including HttpPost attribute - this makes your AJAX call never reach the controller action which uses GET.
  • since I have used request behavior.allow get ,it is necessary to add [httppost],i have seen many articles not use [httppost ] at the Json request, and modelstate is eliminated. Tetsuya Yamamoto
  • By default JSON data uses POST, if you want to allow GET operation then you need to add JsonRequestBehavior.AllowGet. Related: Why is JsonRequestBehavior needed?.
  • i have run program as You say but it also save null values,is it occurs problem in ajax method? - Tetsuya Yamamoto