繁体   English   中英

无法使用 AJAX 和 JQuery 更新 CRUD 中的数据

[英]Couldn't able to Update the data in CRUD using AJAX and JQuery

我在 AJAX 和 JQuery 练习 CRUD 我整理了如何使用 ADO 从数据库添加和获取数据但无法更新 crud 中的数据需要一些帮助!!

这是我的 HomeController.cs


这个程序的每个 function 都将写在这里
 using CRUDAjax.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CRUDAjax.Controllers { public class HomeController: Controller { EmployeeDB empDB = new EmployeeDB(); // GET: Home public ActionResult Index() { return View(); } public JsonResult List() { return Json(empDB.ListAll(), JsonRequestBehavior.AllowGet); } public JsonResult Add(Employee emp) { return Json(empDB.Add(emp), JsonRequestBehavior.AllowGet); } public JsonResult GetbyID(int ID) { var Employee = empDB.ListAll().Find(x => x.EmployeeID.Equals(ID)); return Json(Employee, JsonRequestBehavior.AllowGet); } public JsonResult Update(Employee emp) { return Json(empDB.Update(emp), JsonRequestBehavior.AllowGet); } public JsonResult Delete(int ID) { return Json(empDB.Delete(ID), JsonRequestBehavior.AllowGet); } } }

员工.cs Model

这是员工详细信息的 model

 using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CRUDAjax.Models { public class Employee { public int EmployeeID { get; set; } public string Name { get; set; } public int Age { get; set; } public string State { get; set; } public string Country { get; set; } } } }

员工数据库.cs Model

这里将给出数据库连接,这里我使用了 ADO 方法(连接字符串)

  \`//Load Data in Table when documents is ready  
    > $(document).ready(function () {
    > loadData();
    > });
    >
    > //Load Data function  
    > function loadData() {
    > $.ajax({
    > url: "/Home/List",
    > type: "GET",
    > contentType: "application/json;charset=utf-8",
    > dataType: "json",
    > success: function (result) {
    > var html = '';
    > $.each(result, function (key, item) {
    > html += '\<tr\>';
    > html += '\<td\>' + item.EmployeeID + '\</td\>';
    > html += '\<td\>' + item.Name + '\</td\>';
    > html += '\<td\>' + item.Age + '\</td\>';
    > html += '\<td\>' + item.State + '\</td\>';
    > html += '\<td\>' + item.Country + '\</td\>';
    > html += '\<td\><a href="#">Edit</a> | <a href="#">Delete</a>\</td\>';
    > html += '\</tr\>';
    > });
    > $('.tbody').html(html);
    > },
    > error: function (errormessage) {
    > alert(errormessage.responseText);
    > }
    > });
    > }
    >
    > //Add Data Function  
    > function Add() {
    >
    >     var empObj = {
    >         EmployeeID: $('#EmployeeID').val(),
    >         Name: $('#Name').val(),
    >         Age: $('#Age').val(),
    >         State: $('#State').val(),
    >         Country: $('#Country').val()
    >     };
    >     $.ajax({
    >         url: "/Home/Add",
    >         data: JSON.stringify(empObj),
    >         type: "POST",
    >         contentType: "application/json;charset=utf-8",
    >         dataType: "json",
    >         success: function (result) {
    >             loadData();
    >             $('#myModal').modal('hide');
    >         },
    >         error: function (errormessage) {
    >             alert(errormessage.responseText);
    >         }
    >     });
    >
    > }
    >
    >     //Function for getting the Data Based upon Employee IDfunction getbyID(EmpID) {$('#Name').css('border-color', 'lightgrey');$('#Age').css('border-color', 'lightgrey');$('#State').css('border-color', 'lightgrey');$('#Country').css('border-color', 'lightgrey');$.ajax({url: "/Home/getbyID/" + EmpID,type: "GET",contentType: "application/json;charset=UTF-8",dataType: "json",success: function (result) {$('#EmployeeID').val(result.EmployeeID);$('#Name').val(result.Name);$('#Age').val(result.Age);$('#State').val(result.State);$('#Country').val(result.Country);
    >
    >             $('#myModal').modal('show');
    >             $('#btnUpdate').show();
    >             $('#btnAdd').hide();
    >         },
    >         error: function (errormessage) {
    >             alert(errormessage.responseText);
    >         }
    >     });
    >     return false;
    >
    > }
    >
    > //function for updating employee's record  
    > function Update() {
    >
    >     var empObj = {
    >         EmployeeID: $('#EmployeeID').val(),
    >         Name: $('#Name').val(),
    >         Age: $('#Age').val(),
    >         State: $('#State').val(),
    >         Country: $('#Country').val(),
    >     };
    >     $.ajax({
    >         url: "/Home/Update",
    >         data: JSON.stringify(empObj),
    >         type: "POST",
    >         contentType: "application/json;charset=utf-8",
    >         dataType: "json",
    >         success: function (result) {
    >             loadData();
    >             $('#myModal').modal('hide');
    >             $('#EmployeeID').val("");
    >             $('#Name').val("");
    >             $('#Age').val("");
    >             $('#State').val("");
    >             $('#Country').val("");
    >     
    >         },
    >         error: function (errormessage) {
    >             alert(errormessage.responseText);
    >         }
    >     });
    >
    > }
    
    >     //function for deleting employee's recordfunction Delete(ID) {var ans = confirm("Are you sure you want to delete this Record?");if (ans) {$.ajax({url: "/Home/Delete/" + ID,type: "POST",contentType: "application/json;charset=UTF-8",dataType: "json",success: function (result) {loadData();},error: function (errormessage) {alert(errormessage.responseText);}});}}
    >
    >     //Function for clearing the textboxesfunction clearTextBox() {$('#EmployeeID').val("");$('#Name').val("");$('#Age').val("");$('#State').val("");$('#Country').val("");$('#btnUpdate').hide();$('#btnAdd').show();$('#Name').css('border-color', 'lightgrey');$('#Age').css('border-color', 'lightgrey');$('#State').css('border-color', 'lightgrey');$('#Country').css('border-color', 'lightgrey');}//Valdidation using jqueryfunction validate() {var isValid = true;if ($('#Name').val().trim() == "") {$('#Name').css('border-color', 'Red');isValid = false;}else {$('#Name').css('border-color', 'lightgrey');}if ($('#Age').val().trim() == "") {$('#Age').css('border-color', 'Red');isValid = false;}else {$('#Age').css('border-color', 'lightgrey');}if ($('#State').val().trim() == "") {$('#State').css('border-color', 'Red');isValid = false;}else {$('#State').css('border-color', 'lightgrey');}if ($('#Country').val().trim() == "") {$('#Country').css('border-color', 'Red');isValid = false;}else {$('#Country').css('border-color', 'lightgrey');}return isValid;}`

employee.js(ajax 和 jquery 函数)

这个 javascript where Ajax CRUD的函数会写到哪里

 \`//Load Data in Table when documents is ready > $(document).ready(function () { > loadData(); > }); > > //Load Data function > function loadData() { > $.ajax({ > url: "/Home/List", > type: "GET", > contentType: "application/json;charset=utf-8", > dataType: "json", > success: function (result) { > var html = ''; > $.each(result, function (key, item) { > html += '\<tr\>'; > html += '\<td\>' + item.EmployeeID + '\</td\>'; > html += '\<td\>' + item.Name + '\</td\>'; > html += '\<td\>' + item.Age + '\</td\>'; > html += '\<td\>' + item.State + '\</td\>'; > html += '\<td\>' + item.Country + '\</td\>'; > html += '\<td\><a href="#">Edit</a> | <a href="#">Delete</a>\</td\>'; > html += '\</tr\>'; > }); > $('.tbody').html(html); > }, > error: function (errormessage) { > alert(errormessage.responseText); > } > }); > } > > //Add Data Function > function Add() { > > var empObj = { > EmployeeID: $('#EmployeeID').val(), > Name: $('#Name').val(), > Age: $('#Age').val(), > State: $('#State').val(), > Country: $('#Country').val() > }; > $.ajax({ > url: "/Home/Add", > data: JSON.stringify(empObj), > type: "POST", > contentType: "application/json;charset=utf-8", > dataType: "json", > success: function (result) { > loadData(); > $('#myModal').modal('hide'); > }, > error: function (errormessage) { > alert(errormessage.responseText); > } > }); > > } > > //Function for getting the Data Based upon Employee IDfunction getbyID(EmpID) {$('#Name').css('border-color', 'lightgrey');$('#Age').css('border-color', 'lightgrey');$('#State').css('border-color', 'lightgrey');$('#Country').css('border-color', 'lightgrey');$.ajax({url: "/Home/getbyID/" + EmpID,type: "GET",contentType: "application/json;charset=UTF-8",dataType: "json",success: function (result) {$('#EmployeeID').val(result.EmployeeID);$('#Name').val(result.Name);$('#Age').val(result.Age);$('#State').val(result.State);$('#Country').val(result.Country); > > $('#myModal').modal('show'); > $('#btnUpdate').show(); > $('#btnAdd').hide(); > }, > error: function (errormessage) { > alert(errormessage.responseText); > } > }); > return false; > > } > > //function for updating employee's record > function Update() { > > var empObj = { > EmployeeID: $('#EmployeeID').val(), > Name: $('#Name').val(), > Age: $('#Age').val(), > State: $('#State').val(), > Country: $('#Country').val(), > }; > $.ajax({ > url: "/Home/Update", > data: JSON.stringify(empObj), > type: "POST", > contentType: "application/json;charset=utf-8", > dataType: "json", > success: function (result) { > loadData(); > $('#myModal').modal('hide'); > $('#EmployeeID').val(""); > $('#Name').val(""); > $('#Age').val(""); > $('#State').val(""); > $('#Country').val(""); > > }, > error: function (errormessage) { > alert(errormessage.responseText); > } > }); > > } > //function for deleting employee's recordfunction Delete(ID) {var ans = confirm("Are you sure you want to delete this Record?");if (ans) {$.ajax({url: "/Home/Delete/" + ID,type: "POST",contentType: "application/json;charset=UTF-8",dataType: "json",success: function (result) {loadData();},error: function (errormessage) {alert(errormessage.responseText);}});}} > > //Function for clearing the textboxesfunction clearTextBox() {$('#EmployeeID').val("");$('#Name').val("");$('#Age').val("");$('#State').val("");$('#Country').val("");$('#btnUpdate').hide();$('#btnAdd').show();$('#Name').css('border-color', 'lightgrey');$('#Age').css('border-color', 'lightgrey');$('#State').css('border-color', 'lightgrey');$('#Country').css('border-color', 'lightgrey');}//Valdidation using jqueryfunction validate() {var isValid = true;if ($('#Name').val().trim() == "") {$('#Name').css('border-color', 'Red');isValid = false;}else {$('#Name').css('border-color', 'lightgrey');}if ($('#Age').val().trim() == "") {$('#Age').css('border-color', 'Red');isValid = false;}else {$('#Age').css('border-color', 'lightgrey');}if ($('#State').val().trim() == "") {$('#State').css('border-color', 'Red');isValid = false;}else {$('#State').css('border-color', 'lightgrey');}if ($('#Country').val().trim() == "") {$('#Country').css('border-color', 'Red');isValid = false;}else {$('#Country').css('border-color', 'lightgrey');}return isValid;}`

索引.cshtml


 @{ ViewBag.Title = "Index"; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css"> @*<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>*@ <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <script src="~/Scripts/employee.js"></script> <div class="container"> <h2>Employees Record</h2> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="clearTextBox();">Add New Employee</button><br /><br /> <table class="table table-bordered table-hover"> <thead> <tr> <th> ID </th> <th> Name </th> <th> Age </th> <th> State </th> <th> Country </th> <th> Action </th> </tr> </thead> <tbody class="tbody"></tbody> </table> </div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">X</button> <h4 class="modal-title" id="myModalLabel">Add Employee</h4> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="EmployeeId">ID</label> <input type="text" class="form-control" id="EmployeeID" placeholder="Id" disabled="disabled" /> </div> <div class="form-group"> <label for="EmployeeName">EmployeeName</label> <input type="text" class="form-control" id="Name" placeholder="EmployeeName" /> </div> <div class="form-group"> <label for="Age">Age</label> <input type="text" class="form-control" id="Age" placeholder="Age" /> </div> <div class="form-group"> <label for="EmployeeState">EmployeeState</label> <input type="text" class="form-control" id="State" placeholder="EmployeeState" /> </div> <div class="form-group"> <label for="Country">Country</label> <input type="text" class="form-control" id="Country" placeholder="Country" /> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" id="btnAdd" onclick="return Add();">Add</button> <button type="button" class="btn btn-primary" id="btnUpdate" style="display:none;" onclick="Update();">Update</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div>

您应该使用断点来诊断以下哪项是问题所在:

  1. API是不是没叫? (错误代码?)
    -> 在 controller 中指定“Http 方法”。
    -> 例如)

     [HttpPost] public JsonResult List() { return Json(empDB.ListAll(), JsonRequestBehavior.AllowGet); }


2)API调用是否有效,但是没有参数进来?
-> 使用另一个工具(例如 chrome 开发人员工具)检查是否正在传递参数。

-> 如果这不起作用,请指定参数的类型。
例如)

 public JsonResult Add([FromForm] Employee emp)

3)DB select(或更新)不可能吗?
-> 搜索错误window中的消息并更正错误。
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css">
@*<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>*@
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

通过更新脚本我把它整理好了!!

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM