標籤:mvc control與view互動
<1>
控制器 Home
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using MvcApplication1.Models;namespace MvcApplication1.Controllers{ public class HomeController : Controller { private salesEntities db = new salesEntities(); // // GET: /Home/ public ActionResult Index() { //ViewData.Model = db.T_User.ToList(); //return View(); //以上兩條代碼相當於 return View(db.T_User.ToList()); //括弧裡的db.T_User.ToList()其實就是一個Model } public ActionResult Delete(int id) { //Single:返回序列中滿足指定條件的唯一元素;如果有多個這樣的元素存在,則會引發異常 T_User t_user = db.T_User.Single(t => t.Id == id); return View(t_user); } }}
視圖 Index (首頁)
@*@model MvcApplication1.Models.T_User*@@model IEnumerable<MvcApplication1.Models.T_User>@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>Index</title></head><body> <div> <table border="1"> <tr><th>編號</th><th>姓名</th><th>年齡</th></tr> @foreach (var item in Model) { <tr> <td>@item.Id</td><td>@item.Name</td><td>@item.Age</td> <td>@Html.ActionLink("刪除", "Delete", new { id=item.Id})</td> <td></td> </tr> } </table> </div></body></html>
Delete (刪除資訊頁)
@model MvcApplication1.Models.T_User@{ Layout = null;}<!DOCTYPE html><html><head> <meta name="viewport" content="width=device-width" /> <title>Delete</title></head><body> <h3>你確定要刪除這條記錄嗎?</h3> <fieldset> <legend>T_User</legend> <table> <tr><th>編號:</th><th>@Model.Id</th></tr> <tr><th>姓名:</th><th>@Model.Name</th></tr> <tr><th>年齡:</th><th>@Model.Age</th></tr> </table> </fieldset> @using (Html.BeginForm()) { <p> <input type="submit" value="Delete" /> | @Html.ActionLink("跳轉到首頁", "Index") </p> }</body></html>
MVC [Control與View互動]2