MVC [Control与View交互]2

<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>


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。