0

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?

Talukder
  • 51
  • 2
  • 11

3 Answers3

1

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);
}
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • Being updated code as above it saves null value in the database. – Talukder Nov 27 '18 at 08:38
  • 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`. – Tetsuya Yamamoto Nov 27 '18 at 08:44
  • 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 – Talukder Nov 27 '18 at 08:49
  • 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?](https://stackoverflow.com/questions/8464677/why-is-jsonrequestbehavior-needed). – Tetsuya Yamamoto Nov 27 '18 at 08:53
  • i have run program as You say but it also save null values,is it occurs problem in ajax method? - Tetsuya Yamamoto – Talukder Nov 27 '18 at 09:12
  • The null values occurred because the model binder didn't recognize passed values from JSON string or the request never reach the controller, which I already explained above. Note that the HTTP method and JSON property names matters there, make sure they're exactly match as defined in the viewmodel. – Tetsuya Yamamoto Nov 27 '18 at 09:22
  • It returns correct value when i do not use JSON stringnify in data. passing the property value in data it works ,answer is given-@Tetsuya Yamamoto – Talukder Nov 27 '18 at 09:29
0

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"/>
Doug F
  • 894
  • 2
  • 13
  • 18
  • chanded the input type but it doees not respond and save the data. – Talukder Nov 25 '18 at 22:46
  • When you debug, is the JS being fired at all? – Doug F Nov 25 '18 at 22:48
  • @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. – Doug F Nov 25 '18 at 22:55
0

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");
            }

        });
Talukder
  • 51
  • 2
  • 11