然后右鍵models,新建一個數據模型
注意我添加命名為lianxi
添加后如上
接下來在controllers添加控制器還有在Views中添加視圖
注意控制器lianxi和視圖的名字要一致,然后視圖我是添加了3個分別是Index,insert,Modify,在控制器里分別有三個對應的函數
每當用URL訪問視圖時,他就調用了controllers對應的方法,例如
jiaEntities 就是建立模式時那個數據鏈接的名字
Views里的Index里的代碼如下
Beginform相當於我們平常寫HTNML里的form
@Html.ActionLink就是超鏈接,然后第一個參數為鏈接的文字表示,第2個參數為調用的控制器方法,第3個為傳值,當點擊某個鏈接,就把這個鏈接對於的id賦值給Cid
ViewData["DataList"] 數據就是控制器中Index傳過來的,進過foreach循環得到下面結果
下面是控制器中"修改"功能的代碼
[httpPost]就是向服務器發送時調用的方法
所以當點擊修改時就會執行第一個方法([httpGet])
點擊第一項的修改之后的界面:
這個頁面的代碼如下
model就是從第一個modify還是傳過來的,剛開始我也暈了...
submit的按鈕就是提交這個表單,提交到哪?就是提交到下面這個修改函數了,為什么會到這?因為這個 @using (Html.BeginForm("Modify","lianxi",FormMethod.Post))
上面的函數就是用linq語句修改數據庫...
接下來。。。就是添加的頁面了,其實跟修改的原理都差不多,這里就不多說了直接粘代碼
控制器里的:
[HttpGet]
public ActionResult insert()
{
return View();
}
[HttpPost]
public ActionResult insert(client model) //這個id是通過超鏈接帶過來的
{
try
{
client c = new client();
c.id = model.id;
c.money = model.money;
c.name = model.name ;
db.client.Add(c);
db.SaveChanges();
return RedirectToAction("Index", "lianxi");
}
catch (Exception)
{
//指定對應跳轉的視圖Test下的Test.cshtml文件
return RedirectToAction("Test", "Test");
//return Content("添加失敗" + ex.Message);
}
}
視圖里的有兩個地方
1.Index里的
<td>@Html.ActionLink("添加", "insert")</td>
2.insert里的
@{
ViewBag.Title = "insert";
}
@model mvclianxi.Models.client
<h2>insert</h2>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
@using (Html.BeginForm("Modify","lianxi",FormMethod.Post))
{
<table>
<tr>
<td>@Html.TextBoxFor(model=>model.id)</td>
<td>@Html.TextBoxFor(model=>model.name)</td>
<td>@Html.TextBoxFor(model=>model.money)</td>
<td><input type="submit" value="添加"/>@Html.ActionLink("返回", "index", "lianxi")</td>
</tr>
</table>
}
</body>
</html>
這里不小心用了他的母版頁,也不影響吧,就沒改了
刪除:
視圖中<td>@Html.ActionLink("刪除", "Remove", new { Cid=a.id })</td>
控制器中
public ActionResult Remove() //這個id是通過超鏈接帶過來的
{
try
{
//需要一個實體對象參數
//db.Customers.Remove(new Customer() {CustomerNo = id });
//1,創建要刪除的對象
int id = Convert.ToInt32(Request.QueryString["Cid"]);
client c1 = (from c in db.client where c.id == id select c).SingleOrDefault();
db.client.Remove(c1);
db.SaveChanges();
return RedirectToAction("Index", "lianxi");
}
catch (Exception)
{
//指定對應跳轉的視圖Test下的Test.cshtml文件
return RedirectToAction("Test", "Test");
//return Content("刪除失敗" + ex.Message);
}
}
到此結束。。。