Asp.Net - MVC-实现增删改查

登录:

写入配置文件:

<authentication mode="Forms">
      <forms loginUrl="~/Home/Login" timeout="3000"></forms>
    </authentication>

在UserInfo表中写入验证; 

 

 

 前端页面:

最上面引入:@model AspNetMVC.Models.UserInfo 

AspNetMVC:项目名称,UserInfo 数据库表名

<body>
    <div style="text-align:center">
       @using (Html.BeginForm())
       {
        <table  cellspacing="0" align="center">
            <tr>
                <td>用户名:</td>
                <td>@Html.TextBoxFor(u => u.LogName)</td>
                <td style="color:red">@Html.ValidationMessageFor(u => u.LogName)</td>
            </tr>
            <tr>
                <td>密码:</td>
                <td>@Html.TextBoxFor(u => u.LogPwd)</td>
                <td style="color:red">@Html.ValidationMessageFor(u => u.LogPwd)</td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" name="name" value="登录" /></td>
           </tr>
            <tr>
                <td colspan="2">@Html.ValidationSummary(true)</td>
            </tr>
        </table>
       }
    </div>
</body>

 Home控制器中:

 

 public class HomeController : Controller
    {
        MVCLession31Entities db = new MVCLession31Entities();
        // GET: Home
        //登录
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Login(Login u)
        {
            if (ModelState.IsValid && varLogin(u.LogName,u.LogPwd))
            {
                return RedirectToAction("Index");
            }
            else
            {
                ModelState.AddModelError("","账号或密码错误");
            }
            return View();
        }

        private bool varLogin(string logName, string logPwd)
        {
            var u = (from p in db.Login where p.LogName == logName && p.LogPwd == logPwd select p).FirstOrDefault();
            if (u==null)
            {
                return false;
            }
            else
            {
                FormsAuthentication.SetAuthCookie("logName",false);
                return true;
            }
        }

添加Home控制器:

在引用MVCLession31Entities字段。

查询:

 public class HomeController : Controller
    {
        MVCLession31Entities db = new MVCLession31Entities();
        // GET: Home
        public ActionResult Index()
        {
            //查询员工列表
            ViewBag.EmpList= db.Employee;
            return View();
        }

在Index上右键添加视图到Index页面;

<body>
    <h1 style="text-align:center">员工列表</h1>
    <h3 style="text-align:center"><a href="~/Home/AddEmpForm">添加员工</a></h3>
    <table border="1" width="800" cellspacing="0" align="center">
        <tr>
            <th>员工编号</th>
            <th>部门编号</th>
            <th>员工姓名</th>
            <th>员工电话</th>  
            <th>员工区域</th>
            <th>员工薪资</th>
            <th>操作</th>
        </tr>
        @foreach (var item in ViewBag.EmpList)
        {
        <tr>
            <td>@item.EmpId</td>
            <td>@item.DeptId</td>
            <td>@item.EmpName</td>
            <td>@item.EmpPhone</td>
            <td>@item.EmpArea</td>
            <td>@item.EmpSalary</td>
            <td><a href="EditEmpForm?EmpId=@item.EmpId">编辑</a> &nbsp; &nbsp;  <a href="DeleteEmp?EmpId=@item.EmpId" onclick="return confirm('确定删除吗?')">删除</a></td>  
        </tr>
        }
    </table>
</body>

查询运行结果

联合查询:

public ActionResult Index()
        {
            //ViewBag.EmpList = db.Employee;

            //联合查询
            ViewBag.EmpList = from e in db.Employee
                        join d in db.Dept on e.DeptId equals d.DeptId
                        select new EmployeeViewModel
                        {
                            EmpId  = e.EmpId,
                            DeptName = d.DeptName,
                            EmpName = e.EmpName,
                            EmpPhone = e.EmpPhone,
                            EmpArea = e.EmpArea,
                            EmpSalary = e.EmpSalary
                        };
            return View();
        }

模糊查询:

public class HomeController : Controller
    {
        MVCLession31Entities db = new MVCLession31Entities();
        // GET: Home
        public ActionResult Index()
        {
           

            //联合查询
            ViewBag.EmpList = from e in db.Employee
                              join d in db.Dept on e.DeptId equals d.DeptId
                              select new EmployeeViewModel
                              {
                                  EmpId = e.EmpId,
                                  DeptName = d.DeptName,
                                  EmpName = e.EmpName,
                                  EmpPhone = e.EmpPhone,
                                  EmpArea = e.EmpArea,
                                  EmpSalary = e.EmpSalary
                              };
            ViewBag.DeptList = db.Dept;
            return View();
        }
        [HttpPost]
        public ActionResult Index(string EmpName,int DeptId)
        {
            
            if (EmpName != "" && DeptId != 0)
            {
                //联合查询
                ViewBag.EmpList = from e in db.Employee
                                  join d in db.Dept on e.DeptId equals d.DeptId
                                  where e.EmpName.Contains(EmpName)
                                  where e.DeptId == DeptId
                                  select new EmployeeViewModel
                                  {
                                      EmpId = e.EmpId,
                                      DeptName = d.DeptName,
                                      EmpName = e.EmpName,
                                      EmpPhone = e.EmpPhone,
                                      EmpArea = e.EmpArea,
                                      EmpSalary = e.EmpSalary
                                  };
            }
            else if (EmpName != "" && DeptId == 0)
            {
                //联合查询
                ViewBag.EmpList = from e in db.Employee
                                  join d in db.Dept on e.DeptId equals d.DeptId
                                  where e.EmpName.Contains(EmpName)
                                  select new EmployeeViewModel
                                  {
                                      EmpId = e.EmpId,
                                      DeptName = d.DeptName,
                                      EmpName = e.EmpName,
                                      EmpPhone = e.EmpPhone,
                                      EmpArea = e.EmpArea,
                                      EmpSalary = e.EmpSalary
                                  };
            }
            else if (EmpName == "" && DeptId != 0)
            {
                //联合查询
                ViewBag.EmpList = from e in db.Employee
                                  join d in db.Dept on e.DeptId equals d.DeptId
                                  where e.DeptId == DeptId
                                  select new EmployeeViewModel
                                  {
                                      EmpId = e.EmpId,
                                      DeptName = d.DeptName,
                                      EmpName = e.EmpName,
                                      EmpPhone = e.EmpPhone,
                                      EmpArea = e.EmpArea,
                                      EmpSalary = e.EmpSalary
                                  };
            }
            else
            {
                //联合查询
                ViewBag.EmpList = from e in db.Employee
                                  join d in db.Dept on e.DeptId equals d.DeptId
                                  select new EmployeeViewModel
                                  {
                                      EmpId = e.EmpId,
                                      DeptName = d.DeptName,
                                      EmpName = e.EmpName,
                                      EmpPhone = e.EmpPhone,
                                      EmpArea = e.EmpArea,
                                      EmpSalary = e.EmpSalary
                                  };
            }


            ViewBag.EmpName = EmpName;
            ViewBag.DeptId = DeptId;
            ViewBag.DeptList = db.Dept;

            return View();
        }

 Index查询页面添加员工姓名,部门名称及搜索按钮:

<h1>员工信息列表</h1>
        <form action="/Home/Index" method="post">
            员工姓名: <input type="text" name="EmpName" value="@ViewBag.EmpName" />
            部门名称: <select name="DeptId">
                <option value="0">--请选择--</option>
                @foreach (var item in ViewBag.DeptList)
                {
                    <option value="@item.DeptId" @(ViewBag.DeptId==item.DeptId?"selected":"")>@item.DeptName</option>
                }
            </select>
            <input type="submit" value="查询" />
        </form>
        <a href="/Home/AddEmpForm">添加员工</a>

添加:

 //添加员工页面
       public ActionResult AddEmpForm()
        {
            //查询部门列表
            ViewBag.DeptList = db.Dept;
            return View();
        }

        //添加员工
        public ActionResult AddEmp()
        {
            Employee emp = new Employee()
            {
                DeptId = int.Parse(Request["DeptId"]),
                EmpName = Request["txtName"],
                EmpPhone =Request["txtPhone"],
                EmpArea = Request["txtArea"],
                EmpSalary =decimal.Parse(Request["txtSalary"])
            };
            db.Employee.Add(emp);
            int count = db.SaveChanges();
            if (count>0)
            {
                return Content("<script>alert('添加成功');window.location.href='Index'</script>");
            }
            else
            {
                return Content("<script>alert('添加失败');window.location.href='AddEmpForm'</script>");
            }
         }

在AddEmpForm上右键添加视图: 

<body>
    <form action="~/Home/AddEmp" method="post">
        <div style="text-align:center">
            <table width="500" align="center" border="1" cellspacing="0">
                <tr>
                    <td colspan="2"><h3>添加员工</h3></td>
                </tr>
                <tr>
                    <td>员工部门</td>
                    <td>
                        <select name="DeptId">

                            <option value="0">--请选择--</option>
                            @foreach (var item in ViewBag.DeptList)
                            {
                                <option value="@item.DeptId">@item.DeptName</option>
                            }
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>员工姓名</td>
                    <td><input type="text" name="txtName" /></td>
                </tr>
                <tr>
                    <td>员工电话</td>
                    <td><input type="text" name="txtPhone" /></td>
                </tr>
                <tr>
                    <td>员工地区</td>
                    <td><input type="text" name="txtArea"  /></td>
                </tr>
                <tr>
                    <td>员工薪资</td>
                    <td><input type="text" name="txtSalary" /></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" name="name" value="添加" /></td>  
                </tr>  
            </table>

        </div>


    </form>
</body>

添加页面

修改:

//编辑员工页面
        public ActionResult EditEmpForm()
        {
            //查询部门列表
            ViewBag.DeptList = db.Dept;
            //查询要编辑的列
            ViewBag.emp = db.Employee.Find(int.Parse(Request["EmpId"]));
            return View();
        }
        //修改员工
        public ActionResult EditEmp()
        {
            int EmpId = int.Parse(Request["EmpId"]);
            Employee emp = db.Employee.Find(EmpId);
            emp.DeptId = int.Parse(Request["DeptId"]);
            emp.EmpName = Request["txtName"];
            emp.EmpPhone = Request["txtPhone"];
            emp.EmpArea = Request["txtArea"];
            emp.EmpSalary = decimal.Parse(Request["txtSalary"]);
            int count=db.SaveChanges();
            if (count > 0)
            {
                return Content("<script>alert('修改成功');window.location.href='Index'</script>");
            }
            else
            {
                return Content("<script>alert('修改失败');window.location.href='Index'</script>");
            }
        }

在 EditEmpForm上右键添加视图:

<body>
    <form action="~/Home/EditEmp" method="post">
        <div style="text-align:center">
            <table width="500" align="center" border="1" cellspacing="0">
                <input type="hidden" name="EmpId" value="@ViewBag.emp.EmpId" />
                <tr>
                    <td colspan="2"><h3>修改员工</h3></td>
                </tr>
                <tr>
                    <td>员工部门</td>
                    <td>
                        <select name="DeptId">

                            <option value="0">--请选择--</option>
                            @foreach (var item in ViewBag.DeptList)
                            {
                                <option value="@item.DeptId" @(item.DeptId==ViewBag.emp.DeptId ? "selected":"")>@item.DeptName</option>
                            }
                        </select>
                    </td>
                </tr>
                <tr>
                    <td>员工姓名</td>
                    <td><input type="text" name="txtName" value="@ViewBag.emp.EmpName"/></td>
                </tr>
                <tr>
                    <td>员工电话</td>
                    <td><input type="text" name="txtPhone" value="@ViewBag.emp.EmpPhone" /></td>
                </tr>
                <tr>
                    <td>员工地区</td>
                    <td><input type="text" name="txtArea" value="@ViewBag.emp.EmpArea" /></td>
                </tr>
                <tr>
                    <td>员工薪资</td>
                    <td><input type="text" name="txtSalary" value="@ViewBag.emp.EmpSalary" /></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" name="name" value="修改" /></td>
                </tr>
            </table>

        </div>


    </form>
</body>

修改页面

删除:

 //删除员工
        public ActionResult DeleteEmp()
        {
            int EmpId = int.Parse(Request["EmpId"]);
            Employee emp = db.Employee.Find(EmpId);
            db.Employee.Remove(emp);
            int count = db.SaveChanges();
            if (count > 0)
            {
                return Content("<script>alert('删除成功');window.location.href='Index'</script>");
            }
            else
            {
                return Content("<script>alert('删除失败');window.location.href='Index'</script>");
            }
        }

删除没有前端页面在Index页面中添加

<a href="DeleteEmp?EmpId=@item.EmpId" οnclick="return confirm('确定删除吗?')">删除</a>。

  • 17
    点赞
  • 93
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
ASP.NET MVC 是一种用于创建 Web 应用程序的框架,其中包括实现增删改查等常见操作的功能。下面是一个简单的示例: 1. 创建 Model 类 在 Models 文件夹中创建一个类,用于表示要操作的数据。 ```csharp public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } ``` 2. 创建 DbContext 类 在 Models 文件夹中创建一个继承自 DbContext 的类,用于处理数据的存储和检索。 ```csharp public class MyDbContext : DbContext { public DbSet<Person> Persons { get; set; } } ``` 3. 创建控制器类 在 Controllers 文件夹中创建一个控制器类,用于处理 HTTP 请求并调用 DbContext 的方法。 ```csharp public class PersonController : Controller { private readonly MyDbContext _context; public PersonController(MyDbContext context) { _context = context; } public IActionResult Index() { var persons = _context.Persons.ToList(); return View(persons); } public IActionResult Create() { return View(); } [HttpPost] public IActionResult Create(Person person) { if (ModelState.IsValid) { _context.Persons.Add(person); _context.SaveChanges(); return RedirectToAction("Index"); } return View(person); } public IActionResult Edit(int id) { var person = _context.Persons.FirstOrDefault(p => p.Id == id); if (person == null) { return NotFound(); } return View(person); } [HttpPost] public IActionResult Edit(int id, Person person) { if (id != person.Id) { return NotFound(); } if (ModelState.IsValid) { _context.Persons.Update(person); _context.SaveChanges(); return RedirectToAction("Index"); } return View(person); } public IActionResult Delete(int id) { var person = _context.Persons.FirstOrDefault(p => p.Id == id); if (person == null) { return NotFound(); } return View(person); } [HttpPost, ActionName("Delete")] public IActionResult DeleteConfirmed(int id) { var person = _context.Persons.FirstOrDefault(p => p.Id == id); if (person == null) { return NotFound(); } _context.Persons.Remove(person); _context.SaveChanges(); return RedirectToAction("Index"); } } ``` 4. 创建视图文件 在 Views 文件夹中创建与控制器方法名相对应的视图文件,用于显示数据和接收用户输入。 Index.cshtml: ```html @model List<Person> <table> <thead> <tr> <th>Id</th> <th>Name</th> <th>Age</th> <th></th> </tr> </thead> <tbody> @foreach (var person in Model) { <tr> <td>@person.Id</td> <td>@person.Name</td> <td>@person.Age</td> <td> <a asp-action="Edit" asp-route-id="@person.Id">Edit</a> | <a asp-action="Delete" asp-route-id="@person.Id">Delete</a> </td> </tr> } </tbody> </table> <a asp-action="Create">Create New</a> ``` Create.cshtml: ```html @model Person <form asp-action="Create" method="post"> <div> <label>Name:</label> <input asp-for="Name" /> </div> <div> <label>Age:</label> <input asp-for="Age" /> </div> <button type="submit">Create</button> </form> <a asp-action="Index">Back to List</a> ``` Edit.cshtml: ```html @model Person <form asp-action="Edit" asp-route-id="@Model.Id" method="post"> <div> <label>Name:</label> <input asp-for="Name" /> </div> <div> <label>Age:</label> <input asp-for="Age" /> </div> <button type="submit">Save</button> </form> <a asp-action="Index">Back to List</a> ``` Delete.cshtml: ```html @model Person <p>Are you sure you want to delete this record?</p> <form asp-action="Delete" asp-route-id="@Model.Id" method="post"> <button type="submit">Delete</button> </form> <a asp-action="Index">Back to List</a> ``` 以上就是一个简单ASP.NET MVC 实现增删改查的示例。请注意,这只是一个基础示例,实际项目中可能需要处理更复杂的数据和业务逻辑。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞鹰@四海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值