MVC+EF+AJAX实现增删改查

MVC+EF+AJAX实现增删改查–许俊活

控制器的代码

using MVC_EF.Models;
namespace MVC_EF.Controllers
{
    public class HomeController : Controller
    {
        FreshLiveDBEntities fd = new FreshLiveDBEntities();

        int id = 0;
        //修改
        public ActionResult UpdateUser()
        {
            id = Convert.ToInt32(Request.QueryString["id"].ToString());

            Session["UserId"] = id;

            Users u = fd.Users.Find(id);

            ViewBag.user = u;

            return View();
        }
        [HttpPost]
        public ActionResult UpdateUser(Users user)
        {
           if(Session["UserId"] != null)
            {
                int id = Convert.ToInt32(Session["UserId"]);

                Users u = fd.Users.Find(id);
                u.UserAge = user.UserAge;
                u.UserName = user.UserName;
                fd.Entry(u).State = EntityState.Modified;
                fd.SaveChanges();
            }
            return Content("修改成功"); 
        }
        // GET: Home
        //查询User表
        public ActionResult GetUser()
        {
            ViewBag.UserList = fd.Users.ToList();
            return View(); 
        }

       //添加新增页面
        public ActionResult AddUser()
        {
           
            return View();
        }
        //新增方法
        [HttpPost]
        public ActionResult AddUser(Users us)
        {
            fd.Users.Add(us);
            fd.SaveChanges();
            return Content("0");
        }

        //删除方法
        // POST: Users/Delete/5
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Users users = fd.Users.Find(id);
            fd.Users.Remove(users);
            fd.SaveChanges();
            return RedirectToAction("GetUser");
        }
        //根据名称来搜索异步更新分布视图
        public ActionResult name(string name)
        {
            var UserName = fd.Users.Where(s => s.UserName.Contains(name)).ToList();
            return PartialView("name", UserName);
        }
        public ActionResult Index()
        {
            return View();
        }
    }
}

GetUser视图页面代码

<head>
    <meta name="viewport" content="width=device-width" />
    <title>GetUser</title>
    <script src="~/Scripts/jquery-3.5.1.min.js"></script>
    <script>
        function DeleteUser() {
            $.ajax({
                url: "/Home/DeleteUser",
                type: "post",
                success: function (data) {
                    if (data == "0") {
                        alert("删除成功");
                    } else {
                        alert("删除失败");
                    }
                }
            });
        }
    </script>
</head>
<body>
    <div>
        <ul>
            @foreach (var item in ViewBag.UserList)
            {
            <li>
                账号:@item.UserName,
                密码:@item.UserPwd,
                年龄:@item.UserAge
                <a href="/Home/[email protected]" style="text-decoration:none">修改</a>
                @using (Html.BeginForm())
                {
                    @Html.ActionLink("删除", "Delete", new { id = item.UserID })
                }
            </li> 
            }
        </ul>
       
    </div>
</body>
</html>

AddUser视图页面代码

<head>
    <meta name="viewport" content="width=device-width" />
    <title>AddUser</title>

    <script src="~/Scripts/jquery-3.5.1.min.js"></script>

    <script>
        function AddUser() {
            $.ajax({
                url: "/Home/AddUser",
                type: "post",
                data: {
                    "UserID": $("#UserID").val(),
                    "UserName": $("#UserName").val(),
                    "UserPwd": $("#UserPwd").val(),
                    "UserAge": $("#UserAge").val()
                },
                success: function (data) {
                    alert(111111)
                    if (data == "0") {
                        alert("添加成功");
                    } else {
                        alert("添加失败");
                    }
                }
            });
        }
    </script>
</head>
<body>
    <div>
        编号:
        @Html.TextBox("UserID")
    </div>
    <div>
        账号:
        @Html.TextBox("UserName")
    </div>
    <div>
        密码:
        @Html.Password("UserPwd")
    </div>
    <div>
        年龄:
        @Html.TextBox("UserAge")
    </div>
    <input type="button" value="添加" onclick="AddUser()" />
</body>
</html>

UpdateUser视图页面代码

<head>
    <meta name="viewport" content="width=device-width" />
    <title>UpdateUser</title>
    <script src="~/Scripts/jquery-3.5.1.min.js"></script>
    <script>
        function UpdateUser() {
            $.ajax({
                url: "/Home/UpdateUser",
                type: "post",
                data: {
                    "UserName": $("#UserName").val(),
                    "UserPwd": $("#UserPwd").val(),
                    "UserAge": $("#UserAge").val()
                },
                success: function(data) {
                    if (data == "修改成功") {
                        alert("修改成功");
                    } else {
                        alert("修改失败");
                    }
                }
            });
        }
    </script>
</head>
<body>
    <div>
        <div>
            账号:
           
            @Html.TextBox("UserName", (ViewBag.user as MVC_EF.Models.Users).UserName)
        </div>
        <div>
            密码:
            @Html.Password("UserPwd", (ViewBag.user as MVC_EF.Models.Users).UserPwd)
        </div>
        <div>
            年龄:
            @Html.TextBox("UserAge", (ViewBag.user as MVC_EF.Models.Users).UserAge)
        </div>
        <input type="button" value="修改" onclick="UpdateUser()" />
    </div>
</body>
</html>

Delete视图页面代码

<head>
    <meta name="viewport" content="width=device-width" />
    <title>Delete</title>
</head>
<body>
    <h3>Are you sure you want to delete this?</h3>

    @using (Html.BeginForm()) {

          <input type="submit" value="Delete" class="btn btn-default" />
        }
</body>
</html>

分布视图代码

@model IEnumerable<MVC_EF.Models.Users>
<div id="SearchData">
    <ul>
        @if (Model.Count() == 0)
        {
            <li>暂无数据</li>
        }
        else
        {
            foreach (var item in Model)
            {
                <li>@item.UserName</li>
                <li>@item.UserPwd</li>
                <li>@item.UserAge</li>
            }
        }
    </ul>
    </div>

Index视图代码

<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-3.5.1.min.js"></script>
    <script>
        function cuowu()
        {
            $("#SearchDataList").html("查询有问题!");
        }
    </script>
</head>
<body>
    @using (Ajax.BeginForm("name", "Home", new AjaxOptions
    {
        UpdateTargetId = "SearchData",
        InsertionMode = InsertionMode.Replace,
        HttpMethod = "GET",
        OnFailure = "cuowu"
    }))
    {
        <input type="text" name="name" />
        <input type="submit" value="Search" />
        <div id="SearchDataList"></div>
    }
</body>
</html>

你可能感兴趣的:(MVC)