首页 > 代码库 > MVC Code First

MVC Code First

首先配置好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 = http://www.mamicode.com/from DataItem in db.Books>

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=http://www.mamicode.com/"增加" />>

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=http://www.mamicode.com/"删除" /> |>

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=http://www.mamicode.com/"保存" />>

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