//Index.cshtml

@model IQueryable<MvcExam2.Models.Product>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        @Html.ActionLink("添加", "Add", "ProductCrud")
    </div>
    <div> 
        <table>
            <tr>
                <th>ModelNumber</th>
                <th>ModelName</th>
                <th>UnitCost</th>
                <th>修改</th>
                <th>删除</th>
            </tr>
            @foreach(MvcExam2.Models.Product p in Model)
            {
                <tr>
                    <td>@p.ModelNumber</td>
                    <td>@p.ModelName</td>
                    <td>@p.UnitCost</td>
                    <td>@Html.ActionLink("修改", "Update", "ProductCrud",new RouteValueDictionary(new { id = @p.ProductID }),null)</td>
                    <td>@Html.ActionLink("删除","Delete","ProductCrud", new RouteValueDictionary(new { id = @p.ProductID }), null)</td>
                </tr>
            }
        </table>
    </div>
</body>

</html>

//Add.cshtml

@model MvcExam2.Models.Product
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Add</title>
</head>
<body>
    <div> 
        @using (Html.BeginForm("Add", "ProductCrud", FormMethod.Post))
        {
            <span>ModelNumber:</span>@Html.TextBoxFor(p => p.ModelNumber);<br />
            <span>ModelName:</span>@Html.TextBoxFor(p => p.ModelName);<br />
            <span>UnitCost:</span>@Html.TextBoxFor(p=>p.UnitCost);<br />
            <input type="submit" name="name" value="submit" />
        }
    </div>
</body>

</html>

//Update.cshtml

@model MvcExam2.Models.Product
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Update</title>
</head>
<body>
    <div> 
        @using (Html.BeginForm("Update", "ProductCrud", FormMethod.Post))
        {
            @Html.HiddenFor(p=>p.ProductID)
            <span>ModelNumber:</span>@Html.TextBoxFor(p => p.ModelNumber) <br />
            <span>ModelName:</span>@Html.TextBoxFor(p => p.ModelName) <br />
            <span>UnitCost:</span>@Html.TextBoxFor(p => p.UnitCost) <br />
            <input type="submit" name="name" value="submit" />
        }
    </div>
</body>
</html>

//ProductCrudController

using MvcExam2.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity.Migrations;

namespace MvcExam2.Controllers
{
    public class ProductCrudController : Controller
    {
        DbContext context = new StoreContext();
        // GET: ProductCrud
        public ActionResult Index()
        {
            IQueryable<Product> list = context.Set<Product>();
            return View(list);
        }

        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(Product p)
        {
            p.CategoryID = 14;
            //第一种方法:用curd方法
            //context.Set<Product>().Add(p);
            
            //第二种方法:用状态跟踪
            context.Set<Product>().Attach(p);
            context.Entry(p).State = EntityState.Added;
            int result = context.SaveChanges();
            if (result>0)
            {
                return Redirect(Url.Action("Index"));
            }
            else
            {
                return Redirect(Url.Action("Error"));
            }
           
        }

        public ActionResult Update(int id)
        {
            ViewData.Model= context.Set<Product>().Where(p => p.ProductID == id).FirstOrDefault();
            return View();
        }

        [HttpPost]
        public ActionResult Update(Product p)
        {
            p.CategoryID = 14;
            //第一种方法:用curd方法
            // context.Set<Product>().AddOrUpdate(p);//需要引用System.Data.Entity.Migrations;

            //第二种方法:用状态跟踪
            context.Set<Product>().Attach(p);
            context.Entry(p).State = EntityState.Modified;
            int result = context.SaveChanges();
            if (result > 0)
            {
                return Redirect(Url.Action("Index"));
            }
            else
            {
                return Redirect(Url.Action("Error"));
            }
           
        }

        public ActionResult Delete(int id)
        {
           var product= context.Set<Product>().Where(p => p.ProductID == id).FirstOrDefault();
            //第一种方法:用curd方法
            //context.Set<Product>().Remove(obj);

            //第二种方法:用状态跟踪
            context.Set<Product>().Attach(product);
            context.Entry(product).State = EntityState.Deleted;
            int result = context.SaveChanges();
            if (result > 0)
            {
                return Redirect(Url.Action("Index"));
            }
            else
            {
                return Redirect(Url.Action("Error"));
            }
        }

        public ActionResult Error()
        {
            return View();
        }
    }
}

MVC CRUD 的两种方法的更多相关文章

  1. ASP.NET MVC 实现AJAX跨域请求的两种方法

    通常发送AJAX请求都是在本域内完成的,也就是向本域内的某个URL发送请求,完成部分页面的刷新.但有的时候需要向其它域发送AJAX请求,完成数据的加载,例如Google. 在ASP.NET MVC 框 ...

  2. .NET MVC中登录过滤器拦截的两种方法

    今天给大家介绍两种ASP中过滤器拦截的两种方法. 一种是EF 的HtppModule,另一种则是灵活很多针对MVC的特性类 Attribute 具体什么是特性类可以参考着篇文章:https://www ...

  3. C# web api 返回类型设置为json的两种方法

    每次写博客,第一句话都是这样的:程序员很苦逼,除了会写程序,还得会写博客!当然,希望将来的一天,某位老板看到此博客,给你的程序员职工加点薪资吧!因为程序员的世界除了苦逼就是沉默.我眼中的程序员大多都不 ...

  4. windows下获取IP地址的两种方法

    windows下获取IP地址的两种方法: 一种可以获取IPv4和IPv6,但是需要WSAStartup: 一种只能取到IPv4,但是不需要WSAStartup: 如下: 方法一:(可以获取IPv4和I ...

  5. android 之 启动画面的两种方法

    现在,当我们打开任意的一个app时,其中的大部分都会显示一个启动界面,展示本公司的logo和当前的版本,有的则直接把广告放到了上面.启动画面的可以分为两种设置方式:一种是两个Activity实现,和一 ...

  6. [转载]C#读写txt文件的两种方法介绍

    C#读写txt文件的两种方法介绍 by 大龙哥 1.添加命名空间 System.IO; System.Text; 2.文件的读取 (1).使用FileStream类进行文件的读取,并将它转换成char ...

  7. php如何防止图片盗用/盗链的两种方法(转)

    图片防盗链有什么用? 防止其它网站盗用你的图片,浪费你宝贵的流量.本文章向大家介绍php防止图片盗用/盗链的两种方法 Apache图片重定向方法 设置images目录不充许http访问 Apache服 ...

  8. WPF程序将DLL嵌入到EXE的两种方法

    WPF程序将DLL嵌入到EXE的两种方法 这一篇可以看作是<Visual Studio 版本转换工具WPF版开源了>的续,关于<Visual Studio 版本转换工具WPF版开源了 ...

  9. MongoDB实现分页(两种方法)

    1.插入实验数据 偷懒用下samus,100条. ; i < ; i++) { Document doc = new Document(); doc["ID"] = i; d ...

随机推荐

  1. Hadoop源码分析(MapReduce概论)

    大家都熟悉文件系统,在对HDFS进行分析前,我们并没有花非常多的时间去介绍HDFS的背景.毕竟大家对文件系统的还是有一定的理解的,并且也有非常好的文档.在分析Hadoop的MapReduce部分前,我 ...

  2. arm-linux内存管理学习笔记(1)-内存页表的硬件原理

    linux kernel集中了世界顶尖程序猿们的编程智慧,犹记操作系统课上老师讲操作系统的四大功能:进程调度 内存管理 设备驱动 网络.从事嵌入式软件开发工作,对设备驱动和网络接触的比較多. 而进程调 ...

  3. swift菜鸟入门视频教程-01-基础部分

    本人自己录制的swift菜鸟入门,欢迎大家拍砖,有什么问题能够在这里留言. 主要内容: 常量和变量 凝视 分号 整数 浮点数 类型安全和类型判断 数值型字面量 数值型类型转换 类型别名 布尔值 元组 ...

  4. Oracle数据库零散知识04 --- 其常用内置函数

    1,数值函数 Select abs(-9),--9 绝对值 Mod(5,3),--2 余数 Sign(-9),-- -1 标记 Ceil(9.4),--10 Floor(9.8),--9 Sqrt(1 ...

  5. erlang应用发布

    http://blog.csdn.net/zhangxinrun/article/details/6993892 参考“转载1”和“转载2”就可以了,但需要注意以下两点: 1.如果用rebar - c ...

  6. Erlang 学习笔记

    http://wenku.baidu.com/link?url=AUQR8Hn-e-fEB_lqjXsd8XfapWj1qAK7J05JoBXFib_LlSk5qSOTia8HIxNV1XkeZi-k ...

  7. mingw-w64线程模型:posix vs win32(posix允许使用c++11的std:: thread,但要带一个winpthreads,可能需要额外dll)

    我正在安装 mingw-w64 on Windows,有两个选项: win32线程和posix线程. 我知道win32线程和pthreads之间的区别,但是我不明白这两个选项之间的区别. 我怀疑如果我 ...

  8. sql 声明 将结果select 而混合值

    String slctpsql="select id ,"+uid+","+ddd+","+score+",'"+mar ...

  9. CLR托管内存

    在物理内存中观察CLR托管内存及GC行为   虽然看了一些书,还网络上的一些博文,不过对CLR托管内存细节依然比较模糊.而且因为工作原因总会有很多质疑,想要亲眼看到内存里二进制数据的变化. 所以借助w ...

  10. 让ProgressDialog在setCancelable(false)时按返回键可dismiss

    最近发现Android4.0系统中ProgressDialog设置为setCancelable(true)时,点击ProgressDialog以外的区域也可以让ProgressDialog dismi ...