MVC Code First

來源:互聯網
上載者:User

標籤:codefirst   mvc   

首先配置好web.config

  <connectionStrings>    <add name="BookDbContext" connectionString=" Data Source=.\SQLEXPRESS;Initial Catalog=sales;Persist Security Info=True;Integrated Security=SSPI;"     providerName="System.Data.SqlClient" />  </connectionStrings>

然後在Model裡添加一個Book 類和一個BookDbContext類

Book類

using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace MvcApplication3.Models{    public class Book    {        public int BookID { get; set; }        public string BookName { get; set; }        public string Author { get; set; }        public string Publisher { get; set; }        public decimal Price { get; set; }        public string Remark { get; set; }    }}

BookDbContext類

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data.Entity;namespace MvcApplication3.Models{    /// <summary>    /// BookDbContext代表EF中Book在資料庫中的內容物件,通過DbSet<Book>使實體類與資料庫關聯起來。Books屬性工作表示資料庫中的資料集實體,用來處理資料的存取與更新。BookDbContext派生自DbContext,需要添加System.Data.Entity的引用。    /// </summary>    public class BookDbContext:DbContext    {        public DbSet<Book> Books { get; set; }    }}

添加一個Book控制器

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using MvcApplication3.Models;namespace MvcApplication3.Controllers{    public class BookController : Controller    {        //        // GET: /Book/        BookDbContext db = new BookDbContext();        /// <summary>        /// //查詢出所有的Book對象,組成一個Books,讓它展示在頁面首頁        /// </summary>        /// <returns></returns>        public ActionResult Index()         {            var books = from b in db.Books                        select b;            return View(books.ToList());        }        [HttpGet]        public ActionResult Create()        {            return View();        }        [HttpPost]        public ActionResult Create(Book book)        {            //MVC驗證中所有屬性驗證成功ModelState.IsValid等於true,只要有一個驗證不成功ModelState.IsValid就等於false 所以我們可以通過該屬性來判斷資料的有效性,但有時在資料驗證時有時我們不需要驗證所有的資料,比如登入時只需要驗證使用者名稱及密碼格式是否輸入正確即可。            if (ModelState.IsValid)            {                db.Books.Add(book);                db.SaveChanges();                return RedirectToAction("Index");            }            else            {                return View(book);            }        }        [HttpGet]        public ActionResult Delete(int id)        {            var data = from DataItem in db.Books                       where DataItem.BookID == id                       select DataItem;            ViewData.Model = data.Single();            return View();        }        [HttpPost]        public ActionResult Delete(int id, FormCollection c)        {            //Find()是返回滿足條件的第一個元素,如果沒有該元素,則返回null。            Book book = db.Books.Find(id);            db.Books.Remove(book);            db.SaveChanges();            return RedirectToAction("Index");        }        public ActionResult Edit(int id)        {            //var data = from dataitem in db.Books            //           where dataitem.BookID == id            //           select dataitem;            //ViewData.Model = data.Single();            //return View();            //Find()是返回滿足條件的第一個元素(即:Books中 BookID的的值為id的Book),如果沒有該元素,則返回null。            Book book = db.Books.Find(id);            if (book == null)            {                return RedirectToAction("Index");            }               return View(book);        }        [HttpPost]        public ActionResult Edit(Book newbook)        {            try            {                Book oldbook = db.Books.Find(newbook.BookID);                //使用來自控制器的當前值提供者的值更新指定的模型執行個體                UpdateModel(oldbook);                //將在此上下文中所做的所有更改儲存到基礎資料庫。                db.SaveChanges();                return RedirectToAction("Index");            }            catch (Exception ex)            {                //AddModelError:將指定的錯誤訊息添加到與指定鍵關聯的模型狀態字典的錯誤集合中。                ModelState.AddModelError("", "修改失敗,請查看詳細錯誤資訊" + ex.Message + ex.StackTrace);            }            return View(newbook);        }        public ActionResult Details(int id)        {            //Find()是返回滿足條件的第一個元素(即:Books中 BookID的的值為id的Book),如果沒有該元素,則返回null。            Book book = db.Books.Find(id);            if (book == null)            {                return RedirectToAction("Index");            }            return View(book);        }    }}

view

Index 視圖 首頁

@model IEnumerable<MvcApplication3.Models.Book>@{    ViewBag.Title = "圖書列表-MvcBook";}<h2>    圖書列表</h2><p>    @Html.ActionLink("增加圖書", "Create")</p><table>    <tr>        <th>圖書名稱</th><th>作者</th><th>出版社</th><th>價格</th><th>備忘</th>    </tr>    @foreach (var item in Model)    {        <tr>            <td>                @Html.DisplayFor(modelItem => item.BookName)            </td>            <td>                @Html.DisplayFor(modelItem => item.Author)            </td>            <td>                @Html.DisplayFor(modelItem => item.Publisher)            </td>            <td>                @Html.DisplayFor(modelItem => item.Price)            </td>            <td>                @Html.DisplayFor(modelItem => item.Remark)            </td>            <td>                @Html.ActionLink("編輯", "Edit", new { id = item.BookID }) |                @Html.ActionLink("詳細", "Details", new { id = item.BookID }) |                @Html.ActionLink("刪除", "Delete", new { id = item.BookID })            </td>        </tr>    }</table>


Create

@model MvcApplication3.Models.Book@{    ViewBag.Title = "Create";}<h2>增加</h2>@using (Html.BeginForm()) {    @Html.ValidationSummary(true)    <fieldset>        <legend>Book</legend>        <div class="editor-label">            @Html.LabelFor(model => model.BookName)        </div>        <div class="editor-field">            @Html.EditorFor(model => model.BookName)            @Html.ValidationMessageFor(model => model.BookName)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Author)        </div>        <div class="editor-field">            @Html.EditorFor(model => model.Author)            @Html.ValidationMessageFor(model => model.Author)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Publisher)        </div>        <div class="editor-field">            @Html.EditorFor(model => model.Publisher)            @Html.ValidationMessageFor(model => model.Publisher)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Price)        </div>        <div class="editor-field">            @Html.EditorFor(model => model.Price)            @Html.ValidationMessageFor(model => model.Price)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Remark)        </div>        <div class="editor-field">            @Html.EditorFor(model => model.Remark)            @Html.ValidationMessageFor(model => model.Remark)        </div>        <p>            <input type="submit" value="增加" />        </p>    </fieldset>}<div>    @Html.ActionLink("跳轉到首頁", "Index")</div>@section Scripts {    @Scripts.Render("~/bundles/jqueryval")}

Delete

@model MvcApplication3.Models.Book@{    ViewBag.Title = "Delete";}<h2>Delete</h2><h3>Are you sure you want to delete this?</h3><fieldset>    <legend>Book</legend>    <table>    <tr><th>圖書名稱:</th><th>@Html.DisplayFor(model => model.BookName)</th></tr>    <tr><th>作者:</th><th>@Html.DisplayFor(model => model.Author)</th></tr>    <tr><th>出版社:</th><th>@Html.DisplayFor(model => model.Publisher)</th></tr>    <tr><th>價格:</th><th>@Html.DisplayFor(model => model.Price)</th></tr>    <tr><th>備忘</th><th>@Html.DisplayFor(model => model.Remark)</th></tr>    </table></fieldset>@using (Html.BeginForm()) {    <p>        <input type="submit" value="刪除" /> |        @Html.ActionLink("跳轉到首頁", "Index")    </p>}

Edit

@model MvcApplication3.Models.Book@{    ViewBag.Title = "Edit";}<h2>編輯</h2>@using (Html.BeginForm()) {    @Html.ValidationSummary(true)    <fieldset>        <legend>Book</legend>        @Html.HiddenFor(model => model.BookID)        <div class="editor-label">            @Html.LabelFor(model => model.BookName)        </div>        <div class="editor-field">            @Html.EditorFor(model => model.BookName)            @Html.ValidationMessageFor(model => model.BookName)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Author)        </div>        <div class="editor-field">            @Html.EditorFor(model => model.Author)            @Html.ValidationMessageFor(model => model.Author)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Publisher)        </div>        <div class="editor-field">            @Html.EditorFor(model => model.Publisher)            @Html.ValidationMessageFor(model => model.Publisher)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Price)        </div>        <div class="editor-field">            @Html.EditorFor(model => model.Price)            @Html.ValidationMessageFor(model => model.Price)        </div>        <div class="editor-label">            @Html.LabelFor(model => model.Remark)        </div>        <div class="editor-field">            @Html.EditorFor(model => model.Remark)            @Html.ValidationMessageFor(model => model.Remark)        </div>        <p>            <input type="submit" value="儲存" />        </p>    </fieldset>}<div>    @Html.ActionLink("跳轉到首頁", "Index")</div>@section Scripts {    @Scripts.Render("~/bundles/jqueryval")}

Details

@model MvcApplication3.Models.Book@{    ViewBag.Title = "Details";}<h2>Details</h2><fieldset>    <legend>Book</legend>    <table>    <tr><th>圖書名稱:</th><th>@Html.DisplayFor(model => model.BookName)</th></tr>    <tr><th>作者:</th><th>@Html.DisplayFor(model => model.Author)</th></tr>    <tr><th>出版社:</th><th>@Html.DisplayFor(model => model.Publisher)</th></tr>    <tr><th>價格:</th><th>@Html.DisplayFor(model => model.Price)</th></tr>    <tr><th>備忘</th><th>@Html.DisplayFor(model => model.Remark)</th></tr>    </table></fieldset><p>    @Html.ActionLink("編輯", "Edit", new { id=Model.BookID }) |    @Html.ActionLink("跳轉到首頁", "Index")</p>


MVC Code First

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.