設計ASP.NET MVC4應用程式(2)

by Vivid 19. 十二月 2012 09:58

.NET Magazine國際中文電子雜誌
作 者:許薰尹
審 稿:張智凱
文章編號:N121213102
出刊日期:2012/12/19

在《設計ASP.NET MVC4應用程式(1)》一文中,我們介紹了設計ASP.NET MVC 4網站應用程式的基本概念和設計步驟,而在這邊文章中,我們希望能夠整合ADO.NET實體資料模型 (ADO.NET Entity Data Model),將資料儲存到後端資料庫。

同樣為了簡單說明起見,還是從建立一個專案開始吧,從Visual Studio 2012開發工具 -「檔案」-「新增」-「專案」,在「新增專案」對話盒中選取程式語言,例如本範例選擇「Visual C#」,從「Web」分類中,選取「ASP.NET MVC 4 Web應用程式」,名稱部分使用「MvcApplication1」,按下「確定」鍵。

clip_image002

圖 1:ASP.NET MVC 4 Web應用程式。

選取「基本」專案範本,此範本含有基本網站應用程式的骨架,包含MVC所需的目錄,如Controllers、Models、Views,以及一些基本公用程式碼,如打包與壓縮JavaScript所需的類別,CSS樣式表,檢視引擎選取使用,利用Razor語法。

clip_image004

圖 2:選取「基本」範本。

ASP.NET MVC 4專案預設會引用ADO.NET實體資料模型 5.0版( ADO.NET Entity Framework 5.0版),從「方案總管」專案的參考節點下,你可以看到相關組件都已經參照進來,請參考下圖所示:

clip_image005

圖 3:自動引用Entity Framework 5.0組件。

此外專案中會有一個packages.config檔案,這個檔案是Visual Studio 2012內建的NuGet工具程式用來管理專案安裝了哪一些套件,以及它們的版本用的,若檢視這個檔案,您可以看到預設安裝了EntityFramework的相關資訊,以下是packages.config檔案部分的組態設定資訊:

 

<?xml version = "1.0" encoding = "utf-8"?>
<packages>
  <package id = "EntityFramework" version = "5.0.0" targetFramework = "net45" />
  <package id = "EntityFramework.zh-Hant" version = "5.0.0" targetFramework = "net45" />

我們希望撰寫的網站應用程式能透過ADO.NET Entity Data Model來操作資料,因此讓我們先來加入一個ADO.NET實體資料模型(ADO.NET Entity Data Model),在專案「Models」目錄上按滑鼠右鍵,從快捷選單選取「加入」-「ADO.NET實體資料模型」:

clip_image007

圖 4:加入「ADO.NET實體資料模型」。

在「指定項目的名稱」對話盒,設定項目的名稱為「Model1」,然後按下「確定」鍵。:

clip_image008

圖 5:「指定項目的名稱。

下一步會跳出「實體資料模型精靈」對話盒,我們的範例要從Pubs資料庫建立模型,選取「從資料庫產生」,然後按「下一步」:

clip_image010

圖 6:選取「從資料庫產生」。

下一步設定資料連接(Data Connection),選取「新增連接」按鈕:

clip_image012

圖 7:選取「新增連接」按鈕。

在「連接屬性」對話盒,設定以下資料:

l 資料來源:Microsoft SQL Server (SqlClient)。
l 伺服器名稱:本範例程式將資料庫放在「.\sqlexpress」資料庫中,此處輸入「.\sqlexpress」。
l 登入伺服器:使用Windows驗證。
l 輸入資料庫名稱:選取Pubs資料庫。

clip_image013

圖 8:設定連接資訊。

選取「下一步」按鈕,進到下一個畫面,下方的核取方塊預設會勾選,表示要將資料庫連接字串資訊儲存在組態檔案之中:

clip_image015

圖 9:儲存連接字串到組態檔案。

選取「下一步」按鈕,進到下一個畫面,勾選「stores」資料表,以及勾選「將產生的物件名稱複數化或單數化」來處理模型的命名。

clip_image017

圖 10:選取資料庫物件。

按下「完成」按鈕結束精靈,Visual Studio 2012會在專案中產生一個edmx檔案,包含服務的定義,另外有一個視覺化的edmx設計介面:

clip_image018

圖 11:EDMX設計畫面。

若使用文書處理工具,例如記事本,開啟Model1.edmx檔案,它的定義如下列,其中的Designer區段是給Visual Studio 2012設計階段使用的,Runtime則包含三大區塊:Conceptual Model定義資料模型中的類別,每一個類別稱做一個 Entity,在Entity中會有資料屬性與關聯設定(Association)。Storage Model:定義實體資料庫的各種物件,如資料表、預存程序、使用者定義函數與檢視表等等。Mappings區段設定Conceptual Model與Storage Model之間的對應:

 

<?xml version = "1.0" encoding = "utf-8"?>
<edmx:Edmx Version = "3.0" xmlns:edmx = "http://schemas.microsoft.com/ado/2009/11/edmx">
  <!-- EF Runtime content -->
  <edmx:Runtime>
    <!-- SSDL content -->
    <edmx:StorageModels>
      <Schema Namespace = "pubsModel.Store" Alias = "Self" Provider = "System.Data.SqlClient" ProviderManifestToken = "2008" xmlns:store = "http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns = "http://schemas.microsoft.com/ado/2009/11/edm/ssdl">
        <EntityContainer Name = "pubsModelStoreContainer">
          <EntitySet Name = "stores" EntityType = "pubsModel.Store.stores" store:Type = "Tables" Schema = "dbo" />
        </EntityContainer>
        <EntityType Name = "stores">
          <Key>
            <PropertyRef Name = "stor_id" />
          </Key>
          <Property Name = "stor_id" Type = "char" Nullable = "false" MaxLength = "4" />
          <Property Name = "stor_name" Type = "varchar" MaxLength = "40" />
          <Property Name = "stor_address" Type = "varchar" MaxLength = "40" />
          <Property Name = "city" Type = "varchar" MaxLength = "20" />
          <Property Name = "state" Type = "char" MaxLength = "2" />
          <Property Name = "zip" Type = "char" MaxLength = "5" />
        </EntityType>
      </Schema>
    </edmx:StorageModels>
    <!-- CSDL content -->
    <edmx:ConceptualModels>
      <Schema Namespace = "pubsModel" Alias = "Self" p1:UseStrongSpatialTypes = "false" xmlns:annotation = "http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns:p1 = "http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns = "http://schemas.microsoft.com/ado/2009/11/edm">
        <EntityContainer Name = "pubsEntities" p1:LazyLoadingEnabled = "true">
          <EntitySet Name = "stores" EntityType = "pubsModel.store" />
        </EntityContainer>
        <EntityType Name = "store">
          <Key>
            <PropertyRef Name = "stor_id" />
          </Key>
          <Property Name = "stor_id" Type = "String" Nullable = "false" MaxLength = "4" Unicode = "false" FixedLength = "true" />
          <Property Name = "stor_name" Type = "String" MaxLength = "40" Unicode = "false" FixedLength = "false" />
          <Property Name = "stor_address" Type = "String" MaxLength = "40" Unicode = "false" FixedLength = "false" />
          <Property Name = "city" Type = "String" MaxLength = "20" Unicode = "false" FixedLength = "false" />
          <Property Name = "state" Type = "String" MaxLength = "2" Unicode = "false" FixedLength = "true" />
          <Property Name = "zip" Type = "String" MaxLength = "5" Unicode = "false" FixedLength = "true" />
        </EntityType>
      </Schema>
    </edmx:ConceptualModels>
    <!-- C-S mapping content -->
    <edmx:Mappings>
      <Mapping Space = "C-S" xmlns = "http://schemas.microsoft.com/ado/2009/11/mapping/cs">
        <EntityContainerMapping StorageEntityContainer = "pubsModelStoreContainer" CdmEntityContainer = "pubsEntities">
          <EntitySetMapping Name = "stores">
            <EntityTypeMapping TypeName = "pubsModel.store">
              <MappingFragment StoreEntitySet = "stores">
                <ScalarProperty Name = "stor_id" ColumnName = "stor_id" />
                <ScalarProperty Name = "stor_name" ColumnName = "stor_name" />
                <ScalarProperty Name = "stor_address" ColumnName = "stor_address" />
                <ScalarProperty Name = "city" ColumnName = "city" />
                <ScalarProperty Name = "state" ColumnName = "state" />
                <ScalarProperty Name = "zip" ColumnName = "zip" />
              </MappingFragment>
            </EntityTypeMapping>
          </EntitySetMapping>
        </EntityContainerMapping>
      </Mapping>
    </edmx:Mappings>
  </edmx:Runtime>
  <!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
  <Designer xmlns = "http://schemas.microsoft.com/ado/2009/11/edmx">
    <Connection>
      <DesignerInfoPropertySet>
        <DesignerProperty Name = "MetadataArtifactProcessing" Value = "EmbedInOutputAssembly" />
      </DesignerInfoPropertySet>
    </Connection>
    <Options>
      <DesignerInfoPropertySet>
        <DesignerProperty Name = "ValidateOnBuild" Value = "true" />
        <DesignerProperty Name = "EnablePluralization" Value = "False" />
        <DesignerProperty Name = "IncludeForeignKeysInModel" Value = "True" />
        <DesignerProperty Name = "CodeGenerationStrategy" Value = "無" />
      </DesignerInfoPropertySet>
    </Options>
    <!-- Diagram content (shape and connector positions) -->
    <Diagrams> </Diagrams>
  </Designer>
</edmx:Edmx>

 

另外也會自動在Web.config檔案,設定連線到資料庫所需的連接字串,以下是web.config檔案連接字串區段的內容。

<connectionStrings>

<add name = "DefaultConnection" providerName = "System.Data.SqlClient" connectionString = "Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcApplication2-20121205214634;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcApplication2-20121205214634.mdf" />

<add name = "pubsEntities" connectionString = "metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|
res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\sqlexpress;initial catalog=pubs;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName = "System.Data.EntityClient" />

</connectionStrings>

設計控制器

下一個步驟我們來設計一個整合Entity Framework的控制器。從Visual Studio 2012開發工具-「方案總管」- 你的專案-「Controllers」目錄上方按滑鼠右鍵,從快捷選單選擇「加入」- 「控制器」,請參考下圖所示:

clip_image020

圖 12:加入控制器。

設定控制器名稱為「StoreController」;在這個階段,Scaffold選項可以選擇「具有讀取/寫入動作和檢視、使用Entity Framework的MVC控制器」,模型類別選擇「store」,資料內容類別選取「pubEntities」請參考下圖所示:

clip_image022

圖 13:加入一個整合Entity Framework的控制器。

當你按下「加入」按鈕,Visual Studio 2012就會自動產生StoreController類別,並在其中建立以下動作的程式碼:

l Index:表列store清單資料。
l Details:顯示特定編號的store資料。
l Create:用來建立store資料
l Edit:編修特定的store資料。
l Delete:刪除store資料。

參考以下工具產生的StoreController類別程式碼,其中告一個,pubsEntities型別的db變數,它是用來連接到資料庫,以及處理資料異動的類別:

namespace MvcApplication2.Controllers {
  public class StoreController : Controller {
    private pubsEntities db = new pubsEntities();

    //
    // GET: /Store/

    public ActionResult Index() {
      return View(db.stores.ToList());
    }

    //
    // GET: /Store/Details/5

    public ActionResult Details(string id = null) {
      store store = db.stores.Find(id);
      if (store == null) {
        return HttpNotFound();
      }
      return View(store);
    }

    //
    // GET: /Store/Create

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

    //
    // POST: /Store/Create

    [HttpPost]
    public ActionResult Create(store store) {
      if (ModelState.IsValid) {
        db.stores.Add(store);
        db.SaveChanges();
        return RedirectToAction("Index");
      }

      return View(store);
    }

    //
    // GET: /Store/Edit/5

    public ActionResult Edit(string id = null) {
      store store = db.stores.Find(id);
      if (store == null) {
        return HttpNotFound();
      }
      return View(store);
    }

    //
    // POST: /Store/Edit/5

    [HttpPost]
    public ActionResult Edit(store store) {
      if (ModelState.IsValid) {
        db.Entry(store).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
      }
      return View(store);
    }

    //
    // GET: /Store/Delete/5

    public ActionResult Delete(string id = null) {
      store store = db.stores.Find(id);
      if (store == null) {
        return HttpNotFound();
      }
      return View(store);
    }

    //
    // POST: /Store/Delete/5

    [HttpPost, ActionName("Delete")]
    public ActionResult DeleteConfirmed(string id) {
      store store = db.stores.Find(id);
      db.stores.Remove(store);
      db.SaveChanges();
      return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing) {
      db.Dispose();
      base.Dispose(disposing);
    }
  }
}

Visual Studio 2012也會在Views\store子目錄下產生5個*.cshtml檔案,分別是:Create.cshtml、Delete.cshtml、Details.cshtml、Edit.cshtml與Index.cshtml,請參考下圖所示:

clip_image023

圖 14:Visual Studio 2012自動產生檢視檔案

Views\store子目錄下的檢視檔案內容表列如下:

Create.cshtml

@model MvcApplication2.Models.store

@{
  ViewBag.Title = "Create";
}

<h2> Create </h2>

@using (Html.BeginForm()) {
  @Html.ValidationSummary(true )

  <fieldset>
    <legend> store </legend>

    <div class = "editor-label" >
      @Html.LabelFor( model => model.stor_id )
    </div>
    <div class="editor-field">
      @Html.EditorFor( model => model.stor_id )
      @Html.ValidationMessageFor( model => model.stor_id )
    </div>

    <div class = "editor-label">
      @Html.LabelFor( model => model.stor_name )
    </div>
    <div class = "editor-field">
      @Html.EditorFor( model => model.stor_name )
      @Html.ValidationMessageFor( model => model.stor_name )
    </div>

    <div class = "editor-label">
      @Html.LabelFor( model => model.stor_address )
    </div>
    <div class = "editor-field">
      @Html.EditorFor( model => model.stor_address )
      @Html.ValidationMessageFor( model => model.stor_address )
    </div>

    <div class = "editor-label">
      @Html.LabelFor( model => model.city )
    </div>
    <div class = "editor-field">
      @Html.EditorFor( model => model.city )
      @Html.ValidationMessageFor( model => model.city )
    </div>

    <div class = "editor-label">
      @Html.LabelFor( model => model.state )
    </div>
    <div class = "editor-field">
      @Html.EditorFor( model => model.state )
      @Html.ValidationMessageFor( model => model.state )
    </div>

    <div class = "editor-label">
      @Html.LabelFor( model => model.zip )
    </div>
    <div class = "editor-field">
      @Html.EditorFor( model => model.zip )
      @Html.ValidationMessageFor( model => model.zip )
    </div>

    <p>
      <input type = "submit" value = "Create" />
    </p>
  </fieldset>
}

<div>
  @Html.ActionLink( "Back to List", "Index" )
</div>

@section Scripts {
  @Scripts.Render( "~/bundles/jqueryval" )
}

Delete.cshtml

@model MvcApplication2.Models.store

@{
  ViewBag.Title = "Delete";
}

<h2> Delete </h2>

<h3> Are you sure you want to delete this? </h3>
<fieldset>
  <legend> store </legend>

  <div class = "display-label">
    @Html.DisplayNameFor(model => model.stor_id)
  </div>
  <div class = "display-field">
    @Html.DisplayFor( model => model.stor_id )
  </div>

  <div class = "display-label">
    @Html.DisplayNameFor( model => model.stor_name )
  </div>
  <div class = "display-field">
    @Html.DisplayFor( model => model.stor_name )
  </div>

  <div class = "display-label">
    @Html.DisplayNameFor( model => model.stor_address )
  </div>
  <div class = "display-field">
    @Html.DisplayFor( model => model.stor_address )
  </div>

  <div class = "display-label">
    @Html.DisplayNameFor( model => model.city )
  </div>
  <div class = "display-field">
    @Html.DisplayFor( model => model.city )
  </div>

  <div class = "display-label">
    @Html.DisplayNameFor( model => model.state )
  </div>
  <div class = "display-field">
    @Html.DisplayFor( model => model.state )
  </div>

  <div class = "display-label">
    @Html.DisplayNameFor( model => model.zip )
  </div>
  <div class = "display-field">
    @Html.DisplayFor( model => model.zip )
  </div>
</fieldset>
@using ( Html.BeginForm() ) {
  <p>
    <input type = "submit" value = "Delete" />
    |
        @Html.ActionLink( "Back to List", "Index" )
  </p>
}

Details.cshtml

@model MvcApplication2.Models.store

@{
  ViewBag.Title = "Details";
}

<h2> Details </h2>

<fieldset>
  <legend> store </legend>

  <div class = "display-label">
    @Html.DisplayNameFor( model => model.stor_id )
  </div>
  <div class = "display-field">
    @Html.DisplayFor( model => model.stor_id )
  </div>

  <div class = "display-label">
    @Html.DisplayNameFor( model => model.stor_name )
  </div>
  <div class = "display-field">
    @Html.DisplayFor( model => model.stor_name )
  </div>

  <div class = "display-label">
    @Html.DisplayNameFor(model => model.stor_address)
  </div>
  <div class = "display-field">
    @Html.DisplayFor( model => model.stor_address )
  </div>

  <div class="display-label">
    @Html.DisplayNameFor(model => model.city)
  </div>
  <div class = "display-field">
    @Html.DisplayFor( model => model.city )
  </div>

  <div class = "display-label">
    @Html.DisplayNameFor( model => model.state )
  </div>
  <div class = "display-field">
    @Html.DisplayFor( model => model.state )
  </div>

  <div class="display-label">
    @Html.DisplayNameFor( model => model.zip )
  </div>
  <div class="display-field">
    @Html.DisplayFor( model => model.zip )
  </div>
</fieldset>
<p>
  @Html.ActionLink( "Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
    @Html.ActionLink( "Back to List", "Index")
</p>

 

Edit.cshtml

@model MvcApplication2.Models.store

@{
  ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using ( Html.BeginForm()) {
  @Html.ValidationSummary(true)

  <fieldset>
    <legend> store </legend>

    <div class = "editor-label">
      @Html.LabelFor( model => model.stor_id )
    </div>
    <div class = "editor-field">
      @Html.EditorFor( model => model.stor_id )
      @Html.ValidationMessageFor( model => model.stor_id )
    </div>

    <div class="editor-label">
      @Html.LabelFor( model => model.stor_name )
    </div>
    <div class="editor-field">
      @Html.EditorFor( model => model.stor_name )
      @Html.ValidationMessageFor( model => model.stor_name )
    </div>

    <div class = "editor-label">
      @Html.LabelFor(model => model.stor_address )
    </div>
    <div class="editor-field">
      @Html.EditorFor( model => model.stor_address )
      @Html.ValidationMessageFor( model => model.stor_address )
    </div>

    <div class = "editor-label">
      @Html.LabelFor( model => model.city )
    </div>
    <div class = "editor-field">
      @Html.EditorFor( model => model.city )
      @Html.ValidationMessageFor( model => model.city )
    </div>

    <div class = "editor-label">
      @Html.LabelFor(model => model.state )
    </div>
    <div class = "editor-field">
      @Html.EditorFor( model => model.state )
      @Html.ValidationMessageFor( model => model.state )
    </div>

    <div class = "editor-label">
      @Html.LabelFor( model => model.zip )
    </div>
    <div class = "editor-field">
      @Html.EditorFor( model => model.zip )
      @Html.ValidationMessageFor( model => model.zip )
    </div>

    <p>
      <input type = "submit" value = "Save" />
    </p>
  </fieldset>
}

<div>
  @Html.ActionLink( "Back to List", "Index" )
</div>

@section Scripts {
  @Scripts.Render( "~/bundles/jqueryval" )
}

Index.cshtml

@model IEnumerable<MvcApplication2.Models.store>

@{
  ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
  @Html.ActionLink("Create New", "Create")
</p>
<table>
  <tr>
    <th>
      @Html.DisplayNameFor(model => model.stor_id)
    </th>
    <th>
      @Html.DisplayNameFor(model => model.stor_name)
    </th>
    <th>
      @Html.DisplayNameFor(model => model.stor_address)
    </th>
    <th>
      @Html.DisplayNameFor(model => model.city)
    </th>
    <th>
      @Html.DisplayNameFor(model => model.state)
    </th>
    <th>
      @Html.DisplayNameFor(model => model.zip)
    </th>
    <th></th>
  </tr>

  @foreach (var item in Model) {
    <tr>
      <td>
        @Html.DisplayFor(modelItem => item.stor_id)
      </td>
      <td>
        @Html.DisplayFor(modelItem => item.stor_name)
      </td>
      <td>
        @Html.DisplayFor(modelItem => item.stor_address)
      </td>
      <td>
        @Html.DisplayFor(modelItem => item.city)
      </td>
      <td>
        @Html.DisplayFor(modelItem => item.state)
      </td>
      <td>
        @Html.DisplayFor(modelItem => item.zip)
      </td>
      <td>
        @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
      </td>
    </tr>
  }

</table>

檢視一下Index.cshtml最後的三個叫用Html.ActionLink產生Edit、Details與Delete超連結的語法,預設Visual Studio 2012沒有自傳入主鍵資料,修改程式如下,以便透過主鍵取得要編輯或刪除的資料:

 

@Html.ActionLink("Edit", "Edit", new {  id=item.stor_id }) |
@Html.ActionLink("Details", "Details", new { id=item.stor_id }) |
@Html.ActionLink("Delete", "Delete", new {  id=item.stor_id })

 

 

好了,現在可以按F5執行你的網站應用程式,輸入以下URL:

http://localhost:2969/store

執行結果看起來如下:

clip_image025

圖 15:Index 檢視。

預設會叫用控制器的Index方法,然後利用Index檢視來呈現資料:

 

public ActionResult Index() {
  return View(db.stores.ToList());
}

 

 

當你點選畫面上第一筆資料的「Edit」連結,便會自動送出一個HTTP GET請求到伺服器,使用以下URI位置:

http://localhost:2969/store/Edit/6380

URL Edit後方的「6380」是store的編號,也是資料表的主鍵值,你可以看到畫面如下。

clip_image026

圖 16:Edit 檢視。

伺服端收到HTTP GET請求後,會叫用控制器的Edit 動作做後續處理,利用Find方法找尋模型中對應的store物件,並將找到的物件,利用View方法傳遞到檢視:

 

public ActionResult Edit(string id = null) {
  store store = db.stores.Find(id);
  if (store == null) {
    return HttpNotFound();
  }
  return View(store);
}

 

 

當你點下Edit 檢視上的「Save」按鈕,則會叫用控制器的Edit 動作透過Entity Framework存檔,此方法上方加上HttpPost attribute:

 

[HttpPost]
public ActionResult Edit(store store) {
  if (ModelState.IsValid) {
    db.Entry(store).State = EntityState.Modified;
    db.SaveChanges();
    return RedirectToAction("Index");
  }
  return View(store);
}

同樣地,當網頁執行時,點了畫面上某筆資料的「Details」連結,此請求送到伺服器後會叫用控制器的Details 動作:

 

public ActionResult Details(string id = null) {
  store store = db.stores.Find(id);
  if (store == null) {
    return HttpNotFound();
  }
  return View(store);
}

 

 

Details 檢視呈現的效果如下:

clip_image027

圖 17:Details 檢視。

若點了畫面上某筆資料的「Delete」連結,此請求送到伺服器後會叫用控制器的Delete 動作:

 

public ActionResult Delete(string id = null) {
  store store = db.stores.Find(id);
  if (store == null) {
    return HttpNotFound();
  }
  return View(store);
}

 

 

Delete 檢視呈現的效果如下:

clip_image028

圖 18:Delete 檢視。

當你點下Delete 檢視右方「Delete」按鈕,會叫用伺服端控制器的DeleteConfirmed方法透過Entity Framework執行刪除動作:

 

[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(string id) {
  store store = db.stores.Find(id);
  db.stores.Remove(store);
  db.SaveChanges();
  return RedirectToAction("Index");
}

當你點網頁上方「Create New」連結時,會叫用控制器的Create 動作顯示Create 檢視內容:

 

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

 

 

執行畫面,請參考下圖所示:

clip_image029

圖 19: Create 檢視。

當你點選Create 檢視下方「Create」連結,會叫用控制器的Create方法,在這個方法中利用DbContext的SaveChanges方法將新增到資料模型的資料寫到資料庫。

[HttpPost]
public ActionResult Create(store store) {
   if ( ModelState.IsValid ) {
     db.stores.Add(store);
     db.SaveChanges();
     return RedirectToAction("Index");
   }

   return View(store);
}

總結

在這篇文章中,我們快速地利用ASP.NET MVC 4網站樣版,以及Entity Framework來建立一個資料存取程式,有了開發工具的輔助,幾乎不需要寫太多的程式碼。利用實體資料模型(Entity Framework)的類別,能夠自動處理資料異動的細節。

Tags:

.NET Magazine國際中文電子雜誌 | ASP.NET MVC | 許薰尹Vivid Hsu

新增評論




  Country flag
biuquote
  • 評論
  • 線上預覽
Loading






NET Magazine國際中文電子雜誌

NET Magazine國際中文電子版雜誌,由恆逸資訊創立於2000,自發刊日起迄今已發行超過500篇.NET相關技術文章,擁有超過40000名註冊讀者群。NET Magazine國際中文電子版雜誌希望藉於電子雜誌與NET Developer達到共同學習與技術新知分享,歡迎每一位對.NET 技術有興趣的朋友們多多支持本雜誌,讓作者群們可以有持續性的動力繼續爬文。<請加入免費訂閱>

月分類Month List