ASP.NET MVC使用JavaScript弹出窗口删除gridview记录

时间:2018-11-23 15:44:36

标签: javascript c# asp.net-mvc

我正在遵循一个教程,并使用脚手架来生成大多数控制器和视图。现在,我想在gridview中添加一个额外的按钮模板字段,通过它的onClick事件将使用javascript弹出窗口和确认来删除记录。

<button data-student-id="@item.StudentID" class="btn-link js-delete">Delete</button>

但是当我单击按钮时,出现** 404错误*。如何正确编写?

@model IEnumerable<ContosoSite.Models.Student>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table" id="students">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EnrollmentDate)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.MiddleName)
        </th>
        
        <th></th>
        <th>Delete</th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EnrollmentDate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.MiddleName)
        </td>

        <td>
            @Html.ActionLink("Edit", "Edit", new { id = item.StudentID }) |
            @Html.ActionLink("Details", "Details", new { id = item.StudentID }) |
            @Html.ActionLink("Delete", "Delete", new { id = item.StudentID })
            
        </td>
        <td>
            <button data-student-id="@item.StudentID" class="btn-link js-delete">Delete</button>
        </td>
    </tr>
}

</table>
@section scripts
    {
    <script>
        $(document).ready(function () {
            $("#students .js-delete").on("click", function () {
                var button = $(this);
                if(confirm("are you sure you want to delete this student?"))
                {
                    $.ajax({
                        url: "/Students/delete/" + button.attr("data-student-id"),
                        method: "delete",
                        success: function () {
                            button.Parents("tr").remove();
                            //console.log("success");
                        }

                    })

                };

            });
        });
    </script>
    }

下面是我的观点。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ContosoSite.Models;

namespace ContosoSite.Controllers
{
    public class StudentsController : Controller
    {
        private ContosoUniversityEntities db = new ContosoUniversityEntities();

        // GET: Students
        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }

        // GET: Students/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        // GET: Students/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Students/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "StudentID,LastName,FirstName,EnrollmentDate,MiddleName,HostelID")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(student);
        }

        // GET: Students/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        // POST: Students/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "StudentID,LastName,FirstName,EnrollmentDate,MiddleName,HostelID")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }

        // GET: Students/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        // POST: Students/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Student student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

有一个避免404的更简单的解决方法,让ASP.NET路由为您创建链接,因为硬编码的链接可能会根据不同的因素指向不同的位置,

您可以尝试替换线路

  

url:“ /学生/删除/” + button.attr(“ data-student-id”)

使用

  

url:'@ Url.Action(“删除”,“学生”)/'+   button.attr('data-student-id')

这将使asp.net创建指向您网站的正确链接。