首页 > 其他分享 >使用模态对话框modal 实现CURD新添 修改 删除 Ajax提交

使用模态对话框modal 实现CURD新添 修改 删除 Ajax提交

时间:2023-02-21 17:12:42浏览次数:48  
标签:function 对话框 Employees CURD dbContext id Ajax Employee public

 

 

namespace MvcMovie.Models
{
    public class Employee
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }

    }
}

 

 public class EmployeeViewModel
    {
        public List<Employee>? Employees { get; set; }
        public Employee Employee { get; set; }=new Employee();
    }

 

 1 using Microsoft.AspNetCore.Mvc;
 2 using Microsoft.EntityFrameworkCore;
 3 using MvcMovie.Data;
 4 using MvcMovie.Models;
 5 using MvcMovie.ViewModels;
 6 
 7 namespace MvcMovie.Controllers
 8 {
 9     public class EmployeeController : Controller
10     {
11         MvcMovieContext _dbContext;
12         public EmployeeController(MvcMovieContext dbContext)
13         {
14             _dbContext = dbContext;
15         }
16         public async Task<IActionResult> Index()
17         {
18             return View(await GetViewModel());
19         }
20         [HttpPost]
21         [ValidateAntiForgeryToken]
22         public async Task<IActionResult> Create(EmployeeViewModel viewModel)
23         {
24             if (!ModelState.IsValid)
25             {
26                 return View("Index", await GetViewModel());
27             }
28             Employee newModel = new Employee();
29             newModel.Name = viewModel.Employee.Name;
30             _dbContext.Employees.Add(newModel);
31             _dbContext.SaveChanges();
32             return RedirectToAction("Index");
33         }
34         [HttpPost]
35         [ValidateAntiForgeryToken]
36         public IActionResult Update(EmployeeViewModel viewModel)
37         {
38             var empfromDb = _dbContext.Employees.Find(viewModel.Employee.Id);
39             empfromDb.Name = viewModel.Employee.Name;
40             _dbContext.Employees.Update(empfromDb);
41             _dbContext.SaveChanges();
42             return RedirectToAction("Index");
43         }
44         [HttpPost]
45         public JsonResult Delete(int id)
46         {
47             bool result = false;
48             var model = _dbContext.Employees.Find(id);
49             if (model != null)
50             {
51                 result = true;
52                 _dbContext.Employees.Remove(model);
53                 _dbContext.SaveChanges();
54             }
55             return Json(result);
56         }
57         public JsonResult GetEmployee(int id)
58         {
59             var model = _dbContext.Employees.Find(id);
60             return Json(model);
61         }
62 
63         private async Task<EmployeeViewModel> GetViewModel()
64         {
65             EmployeeViewModel viewModel = new EmployeeViewModel();
66             viewModel.Employees = await _dbContext.Employees.ToListAsync();
67             return viewModel;
68         }
69        
70     }
71 }
@model EmployeeViewModel

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
    新添员工
</button>

<!-- 新添员工 -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div id="saveForm" class="modal-content" >
            <form id="saveForm" asp-action="Create" method="post">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="exampleModalLabel">新添员工</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label asp-for="Employee.Name" class="control-lable"></label>
                        <input asp-for="Employee.Name" class="form-control" />
                        <span asp-validation-for="Employee.Name" class="text-danger"></span>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btnCancel" data-bs-dismiss="modal">Close</button>
                    <button id="btnSave" type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!--删除员工-->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="saveForm"  method="post">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="exampleModalLabel">删除员工</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <h2>你真的想删除这个员工吗?</h2>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btnCancel" data-bs-dismiss="modal">Close</button>
                    <button id="btnDelete" type="button" class="btn btn-primary">删除</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!--编辑-->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form asp-action="Update" id="EditForm" method="post">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <input class="updateId" type="hidden" asp-for="Employee.Id" />
                        <label asp-for="Employee.Name" class="control-lable"></label>
                        <input id="empName" asp-for="Employee.Name" class="form-control" />
                        <span asp-validation-for="Employee.Name" class="text-danger"></span>

                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btnCancel" data-bs-dismiss="modal">Close</button>
                    <button id="btnSave" type="submit" class="btn btn-primary">修改</button>
                </div>
            </form>
        </div>
    </div>
</div>

<input type="hidden" id="EmpId" />

<table class="table">
    <thead class="thead-dark">
        <tr>
            <th scope="col">#</th>
            <th scope="col">Name</th>
            <th scope="col">Actions</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.Employees)
        {
            <tr>
                <th scope="row">@item.Id</th>
                <td>@item.Name</td>
                <td>
                    <a class="btn btn-danger" onclick="EditForm(@item.Id)" id="EditForm">编辑</a>|
                    <a class="btn btn-danger" onclick="DeleteForm(@item.Id)" id="showModal" >删除</a>
                </td>
            </tr>
        }
    </tbody>
</table>

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
     <script>
        //保存当前Id到 EmpId 文本控件
        var DeleteForm = function (id) {
            $("#EmpId").val(id);
            $("#deleteModal").modal('show');
        }
        //打开对话框并初始化控件
        var EditForm = function (id) {
            $.ajax({
                type: "GET",
                url: "/Employee/GetEmployee",
                data: { id: id},
                success: function (employee) {
                    $("#editModal").modal('show');
                    $("#empName").val(employee.name);
                    $(".updateId").val(employee.id);
                }
            })
        }
         $(document).ready(function()
         {
             //$("#btnSave").click(function()
             //{
             //    var empForm=$("#saveForm").serialize();
             //    $.ajax({
             //        type:"POST",
             //        url:"/Employee/Create",
             //        data:empForm,
             //        success:function(){
             //            window.location.href="/Employee/Index";
             //        }
             //    })
             //})
             //当点取消按钮时,导航到首页
             $(".btnCancel").click(function(){
                 window.location.href="/Employee/Index";
             })
          
             $("#btnDelete").click(function(){
                 var currentId=$("#EmpId").val();
                 $.ajax({
                     type:"POST",
                     url:"/Employee/Delete",
                    data: { id: currentId },
                     success:function(result){
                         if(result){
                             $("#EmpId").val(null);
                             window.location.href="/Employee/Index";
                         }
                         else{
                             alert("删除失败");
                         }
                     }
                 })
             })
            
             
         })
     </script>
}

 

 

 

标签:function,对话框,Employees,CURD,dbContext,id,Ajax,Employee,public
From: https://www.cnblogs.com/friend/p/17141672.html

相关文章

  • QFileDialog -文件对话框
    QFileDialog继承了QDialog,具有父类的各种方法。QFileDialog提供了一个对话框,允许用户选择文件或者目录,也允许用户遍历文件系统,用以选择一个或多个文件或者目录。常用方法......
  • AJAX概念
    AJAX概念:ASynchronousJavaScriptAndXML异步的JavaScript和XML1异步和同步:客户端和服务器端相互通信的基础上客户端必须等待服务端的响应在等待的期......
  • 用jquery.form.js 实现ajax提交含有上传文件和普通字段的表单
    前两天用到ajax提交含上传图片的表单。实现的功能比较简单,但是使用ajax提交表单form.serialize只能实现普通的字段提交,上传图片却不能使用。网上很多都是推荐使用jquer......
  • QWidget设置成模态对话框并弹框显示
    正确的做法: 1、FormProcessRoi*form=newFormProcessRoi(this);//只能用指针,不能实例化为对象//Qt::NonModal不阻塞//Qt::WindowModal阻塞父窗口,所有祖先窗......
  • AJAX-JQuery实现方式-ajax()、JQuery实现方式-ajax()-其他键值JQuery实现方式-get&pos
    AJAX-实现-JQuery实现方式-ajax()02-JQuery实现方式1.html页面<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>AJAX-实现-JQuery实现......
  • java环境搭建问题之——此环境变量太大。此对话框允许将值设置为最长2047个字符。“
    系列文章目录文章目录​​系列文章目录​​​​前言​​​​一、解决办法​​​​办法二​​前言安装完jdk1.8,之后,要添加环境变量,之前添加都没事,突然就加不了了,情况很急,这......
  • AJAX-概念、AJAX-实现-原生JS方式
    AJAX-概念概念:ASynchronousJavaScriptAndXML异步的JavaScript和XML1.异步和同步:客户端和服务器端相互通信的基础上*客户端必须等待服......
  • ajax 获取 后台数据,前端 select option中显示出来
    ajax获取后台数据,前端selectoption中显示出来functiongetcity(){varpvid=$('pvid');varajax=newAjax.Request('getadm......
  • PHP处理Ajax请求与Ajax跨域
    前端页面发送Ajax到服务端,服务端可以判断请求是否是Ajax请求,另外,对于跨域的Ajax请求,我们知道有JSONP方法,那服务器PHP该如何处理这些JSONP请求呢,以及如何处理不是jsonp请求的......
  • Ajax基础
    什么是Ajax(AsynchronousJavascriptAndXML)? 异步刷新请求(服务),一般是在无需请求整个页面时执行的操作,局部页面发生改变。为什么使用Ajax? 无刷新:不用刷新整个页面,只刷新局......