我在 AJAX 和 JQuery 中練習 CRUD 我整理了如何使用 ADO 從資料庫中添加和獲取資料,但無法更新 crud 中的資料需要一些幫助!
這是我的 HomeController.cs
這里程式的每個函式都將寫在這里
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);
}
}
}
Employee.cs 模型
這是員工詳細資訊的模型
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; }
}
}
}
EmployeeDB.cs 模型
這里將給出資料庫連接,這里我使用了 ADO 方法(連接字串)
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
> namespace CRUDAjax.Models {
public class EmployeeDB {
string cs = ConfigurationManager.ConnectionStrings["DBCS"\].ConnectionString;
>
> //Return list of all Employees
> public List\<Employee\> ListAll()
> {
> List\<Employee\> lst = new List\<Employee\>();
> using (SqlConnection con = new SqlConnection(cs))
> {
> con.Open();
> SqlCommand com = new SqlCommand("SelectEmployee", con);
> com.CommandType = CommandType.StoredProcedure;
> SqlDataReader rdr = com.ExecuteReader();
> while (rdr.Read())
> {
> lst.Add(new Employee
> {
> EmployeeID = Convert.ToInt32(rdr\["EmployeeId"\]),
> Name = rdr\["Name"\].ToString(),
> Age = Convert.ToInt32(rdr\["Age"\]),
> State = rdr\["State"\].ToString(),
> Country = rdr\["Country"\].ToString(),
> });
> }
> return lst;
> }
> }
>
> //Method for Adding an Employee
> public int Add(Employee emp)
> {
> int i;
> using (SqlConnection con = new SqlConnection(cs))
> {
> con.Open();
> SqlCommand com = new SqlCommand("InsertUpdateEmployee", con);
> com.CommandType = CommandType.StoredProcedure;
> com.Parameters.AddWithValue("@Id", emp.EmployeeID);
> com.Parameters.AddWithValue("@Name", emp.Name);
> com.Parameters.AddWithValue("@Age", emp.Age);
> com.Parameters.AddWithValue("@State", emp.State);
> com.Parameters.AddWithValue("@Country", emp.Country);
> com.Parameters.AddWithValue("@Action", "Insert");
> i = com.ExecuteNonQuery();
> }
> return i;
> }
>
> //Method for Updating Employee record
> public int Update(Employee emp)
> {
> int i;
> using (SqlConnection con = new SqlConnection(cs))
> {
> con.Open();
> SqlCommand com = new SqlCommand("InsertUpdateEmployee", con);
> com.CommandType = CommandType.StoredProcedure;
> com.Parameters.AddWithValue("@Id", emp.EmployeeID);
> com.Parameters.AddWithValue("@Name", emp.Name);
> com.Parameters.AddWithValue("@Age", emp.Age);
> com.Parameters.AddWithValue("@State", emp.State);
> com.Parameters.AddWithValue("@Country", emp.Country);
> com.Parameters.AddWithValue("@Action", "Update");
> i = com.ExecuteNonQuery();
> }
> return i;
> }
>
> //Method for Deleting an Employee
> public int Delete(int ID)
> {
> int i;
> using (SqlConnection con = new SqlConnection(cs))
> {
> con.Open();
> SqlCommand com = new SqlCommand("DeleteEmployee", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Id", ID);
i = com.ExecuteNonQuery();
}
return i;
> }
> }
>
> }
employee.js(ajax 和 jquery 函式)
這是將撰寫 CRUD 的 Ajax 函式的 javascript
\`//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>
uj5u.com熱心網友回復:
您應該使用斷點來診斷以下哪個是問題:
API沒有被呼叫嗎?(錯誤代碼?)
-> 在控制器中指定“Http 方法”。
-> 例如)[HttpPost] public JsonResult List() { return Json(empDB.ListAll(), JsonRequestBehavior.AllowGet); }
2)API呼叫是否有效,但沒有引數進來?
-> 使用其他工具(例如 chrome 開發者工具)檢查是否正在傳遞引數。
-> 如果這不起作用,請指定引數的型別。
例如)
public JsonResult Add([FromForm] Employee emp)
3)資料庫選擇(或更新)不可能嗎?
-> 在錯誤視窗中搜索訊息并更正錯誤。
uj5u.com熱心網友回復:
<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>
通過更新我整理的腳本!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/453509.html
標籤:javascript C# jQuery 阿贾克斯 asp.net-mvc
