简体   繁体   English

如何在ASP.NET MVC中使用jQuery / Ajax将数据插入数据库?

[英]How to insert data into a 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. 试图使用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] 控制器[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. 由于您制作的JS函数正在处理帖子,因此您无需使用“提交”按钮,这将导致整个页面的重新加载。 Just use a normal button. 只需使用普通按钮即可。

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

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. 1)您已订阅了提交按钮的click事件,而没有阻止提交表单的默认操作。 This triggered POST action which redirect away into the controller action and reload the page without leaving any time for AJAX function to execute. 这触发了POST操作,该操作重定向到控制器操作并重新加载页面,而没有任何时间执行AJAX函数。 You should use preventDefault() to cancel the default action of the button. 您应该使用preventDefault()来取消按钮的默认操作。

2) The controller which receives AJAX callback does not have [HttpPost] attribute while type: "POST" option is used. 2)当使用type: "POST"选项时,接收AJAX回调的控制器没有[HttpPost]属性。 Consider adding [HttpPost] attribute on top of controller name. 考虑在控制器名称的顶部添加[HttpPost]属性。

3) Your AJAX property names list does not match with property names defined inside model class. 3)您的AJAX属性名称列表与模型类中定义的属性名称不匹配。 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: 因此,AJAX回调应按照以下示例进行设置:

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) JS(点击事件)

$('#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);
}

After changing the ajax() method like below it works. 像下面一样更改ajax()方法后,它可以工作。

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

        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 AJAX (ASP.NET MVC) 将数据插入数据库 - Insert data to database using AJAX (ASP.NET MVC ) 使用 ASP.NET 6.0 MVC 应用程序中的 jQuery AJAX 将数据插入数据库 - Insert data into database using jQuery AJAX in ASP.NET 6.0 MVC Application 在asp.net中使用jQuery Ajax将值插入数据库 - To insert values into database using jquery ajax in asp.net How to insert HTML table data into SQL Server in a single batch by using jquery ajax and structured parameter with ASP.NET MVC controller - How to insert HTML table data into SQL Server in a single batch by using jquery ajax and structured parameter with ASP.NET MVC controller 在Asp.net C#中使用jQuery Ajax插入数据[数据库MySQL] - Insert Data Using jQuery Ajax in Asp.net C# [Database MySQL] 在ASP.NET C#中使用jquery ajax将数据插入sql数据库 - insert data into sql database using jquery ajax in asp.net c# 在ASP.NET MVC和AJAX jQuery数据表中使用数据注释 - Using Data Annotations in ASP.NET MVC with AJAX jQuery Datatables 如何使用 asp.net 核心 mvc 6 将图像插入数据库? - How to insert images into database using asp.net core mvc 6? 如何在asp.net mvc中使用下拉列表在数据库中插入记录? - How to Insert a record in database using dropdownlist In asp.net mvc? 如何使用ASP.NET MVC代码将值插入数据库 - How to insert values into the database using asp.net mvc code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM