mvc3.0 +linq 操作数据库中表的数据(ps:本人菜鸟刚学)
1:添加控制器类文件HomeController.cs其代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MvcTestData.Models; namespace MvcTestData.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { TestDataContext txtData = new TestDataContext(); var result=from info in txtData.StuTable select info; ViewData["data"] = result; return View(result); } public ActionResult Add(FormCollection form) { string id =form["StuId"]; string name=form["StuName"]; string sex = form["StuSex"]; int age = int.Parse(form["StuAge"]); string address = form["StuAddress"]; StuTable stu = new StuTable(); stu.StuId = id; stu.StuName = name; stu.StuSex = sex; stu.StuAge = age; stu.StuAddress = address; try { using (var db = new TestDataContext()) { db.StuTable.InsertOnSubmit(stu); db.SubmitChanges(); ViewData["result"] = "ok"; } } catch { ViewData["result"] = "fail"; throw; } return View("Add"); } public ViewResult AddInfo() { return View("AddInfo"); } public ViewResult Delete() { int id = Int16.Parse(Request.Form["id"]); try { using (var db = new TestDataContext()) { db.StuTable.DeleteOnSubmit(db.StuTable.First(info => info.ID == id)); db.SubmitChanges(); ViewData["result"] = "ok"; } } catch { ViewData["result"] = "fail"; throw; } return View("Delete"); } } }
2:为models文件夹添加linq to sql 类文件然后把数据库中的表copy 进来
3:为控制器中的Action添加各自的视图
4 视图Index.cshtml的代码
@using MvcTestData.Models <!DOCTYPE html> <html> <head> <title>Index</title> </head> <body> <div> <table border="0" cellspacing="0" cellpadding="0" width="100%" style="text-align:center" > <tr> <th>序号</th><th>学号</th><th>姓名</th><th>性别</th><th>年龄</th><th>住址</th><th >操作</th> </tr> @foreach (StuTable info in (ViewData["data"] as IEnumerable<StuTable>)) { <tr> <td>@info.ID</td> <td>@info.StuId </td> <td>@info.StuName </td> <td>@info.StuSex </td> <td>@info.StuAge </td> <td>@info.StuAddress </td> <td > <form action="/Home/Delete" method="post"> <input type="hidden" name="id" value="@info.ID"/> <input type="submit" value="删除"/> </form> </td> </tr> } </table> <br/> @Html.ActionLink("添加个人信息","AddInfo","Home") </div> </body> </html>
5 视图 Add.cshtml的代码
@model MvcTestData.Models.StuTable @{ ViewBag.Title = "Add"; } @if(ViewData["result"].Equals("ok")) { <p>添加成功</p> } else { <p>添加失败</p> }
6 视图AddInfo.cshtml代码
@model MvcTestData.Models.StuTable @{ ViewBag.Title = "AddInfo"; } <h2>AddInfo</h2> <body> @using(Html.BeginForm("Add","Home",FormMethod.Post)) { <p>Student 学号:@Html.TextBoxFor(x=>x.StuId)</p> <p>Student 姓名:@Html.TextBoxFor(x=>x.StuName)</p> <p>Student 性别:@Html.TextBoxFor(x=>x.StuSex)</p> <p>Student 年龄:@Html.TextBoxFor(x=>x.StuAge)</p> <p>Student 住址:@Html.TextBoxFor(x=>x.StuAddress)</p> <input type="submit" value="Add" /> } </body>
7 视图Delete.cshtml代码
@model MvcTestData.Models.StuTable @{ ViewBag.Title = "Delete"; } @if (ViewData["result"].Equals("ok")) { <p>删除成功</p> } else { <p>删除失败</p> }
8 最终测试结果图: