ASP.NET MVC 開發實例:簡單留言板的開發

ASP.NET MVC 開發實例:簡單留言板的開發

上一個例子 我們使用手動創建一個注冊會員的實例,熟悉了一下視圖、控制器、MODEL之間的關聯,對MVC有了一個初步的了解。

本例子是一個ASP.NET MVC開發簡單留言板的例程,使用了MVC已經配置好的組件進行開發,也許你會驚訝于開發的速度,在還沒怎么動手,程序已經可以寫入數據庫了,增刪改一個不少的呢!本例程參考《ASP.NET MVC 4開發指南》第三章:新手上路初體驗。有需要的朋友請購買本書。

現在,我們從新建項目開始。

新建一個項目,名字取為GuestBook,點擊確定。

在彈出來的新建項目窗口上,選擇為MVC模板。

構建文件需要一點時間,完成了以后按F5已經可以運行網站了。可以看見,ASP.NET MVC為我們打造了一個美觀大方的首頁。

下面我們來創建數據模型:

第一步:在“解決方案資源管理器”窗口選擇Models目錄,右擊,在彈出的菜單選擇添加-類,取名為Guestbook.cs,點擊添加。

第二步:修改Guestbook.cs代碼,定義出一個基本留言板所需要的數據類型.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GuestBook.Models
{
    public class Guestbook
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Content { get; set; }
    }
}

第三步:點擊Ctrl+Shift+B,生成解決方案。也就是將這個類進行編譯。

做過上一個實例的朋友一定會明白,為什么需要進行編譯。接下來,我們將創建控制器、動作和視圖。

第一步:在“解決方案資源管理器”窗口選擇Controllers目錄,右擊,在彈出的菜單選擇控制器。

第二步:選擇包含視圖的MVC5控制器(使用Entity Framework)

第三步:彈出添加控制器的對話框,模型類選擇Guestbook(GuestBook.Models),數據上下文點擊右端的加號,會自動彈出一個對話框,默認“GuestBook.Models.GuestBookContext”點擊添加,控制器默認為GuestbooksController,點擊添加。

好了,完成了留言板了。

點擊F5,http://localhost:/Guestbooks/Index 瀏覽一下,是不是已經有了,還有Create New等頁面十分標致。

的確,這樣的頁面很省事,但滿足不了我們的要求,一般來說,一個自動生成的程序,我們需要對它頁面UI、程序功能進行修改。頁面修改其實不難,一些功能上的修改就顯得有點困難了。

例如,像上一節的例子一樣,我們需要增加一些輸入驗證,以防止用戶一些無效的輸入。你也許會說,這個不難,前面我學習了。于是打開Guestbook.cs進行修改。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace GuestBook.Models
{
    public class Guestbook
    {
        public int Id { get; set; }
        [Required(ErrorMessage = "請輸入用戶名。")]
        public string Name { get; set; }
        [Required(ErrorMessage = "請輸入Email。")]
        public string Email { get; set; }
        [Required(ErrorMessage = "請輸入內容。")]
        public string Content { get; set; }
    }
}

然后運行一看,傻眼了,出錯了。

這是因為在使用EF Code First時,當Model發生變更時,默認會引起System.InvalidOperationException異常。

那么要怎么辦呢?

解決問題的最簡單的方法就是砍掉整個數據庫重建。關于如何遷移數據,點擊 http://msdn.microsoft.com/en-us/data/jj591621.aspx 有詳細說明。現在我們在新建整段代碼,數據丟失并沒有多大問題。

打開Global.asax.cs,在protected void Application_Start() 下面輸入代碼:

 protected void Application_Start()
        {
            System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<GuestBook.Models.GuestBookContext>());

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

運行一下,錯誤解除。當然數據也就消失了。

現在可以隨意的修改Guestbook.cs文件了,例如做如下修改:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace GuestBook.Models
{
    public class Guestbook
    {
        public int Id { get; set; }
        [Required]
        [DisplayName("姓名")]
        public string Name { get; set; }
        [Required]
        [DisplayName("電子郵件")]
        public string Email { get; set; }
        [Required]
        [DisplayName("內容")]
        public string Content { get; set; }
    }
}

這樣我們就可以放心調試,數據丟失了也沒什么大問題。一直修改到我們滿意為止。

但是如果將來產品上線了,要記得去掉剛剛寫在Global.asax.cs文件上的代碼。否則修改模型的話,數據又將丟失。

下面進行代碼重構,留言板只需要顯示留言和增加留言。對頁面進行重構的同時增強對MVC的認識。

首先,打開Controller文件夾,對GuestbooksController.cs文件進行修改。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using GuestBook.Models;

namespace GuestBook.Controllers
{
    public class GuestbooksController : Controller
    {
        private GuestBookContext db = new GuestBookContext();
        // 顯示留言
        // GET: Guestbooks
        public ActionResult Index()
        {
            return View(db.Guestbooks.ToList());
        }

        // GET: Guestbooks/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Guestbook guestbook = db.Guestbooks.Find(id);
            if (guestbook == null)
            {
                return HttpNotFound();
            }
            return View(guestbook);
        }

        // GET: Guestbooks/Create
        public ActionResult Write()
        {
            return View();
        }

        // POST: Guestbooks/Create
        // 為了防止“過多發布”攻擊,請啟用要綁定到的特定屬性,有關 
        // 詳細信息,請參閱 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Write([Bind(Include = "Id,Name,Email,Content")] Guestbook guestbook)
        {
            if (ModelState.IsValid)
            {
                db.Guestbooks.Add(guestbook);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(guestbook);
        }

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

可以看出,我們已經將編輯、刪除的有關代碼給去掉(因為留言板不需要這些功能,如果需要也是在管理員的權限下面,此處不做這方面的討論),將Create改成Write,同樣的,我們也需要將Create.cshtml改名為Write.cshtml,下面我們看看它的源代碼:

@model GuestBook.Models.Guestbook

@{
    ViewBag.Title = "Write";
}

<h2>留下足跡</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Guestbook</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Content, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Content, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Content, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="發表留言" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("回到留言列表", "Index")
</div>

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

運行測試成功,頁面自動返回到index處,這個頁面也需要進行修改,打開index.cshtml文件:

@model IEnumerable<GuestBook.Models.Guestbook>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("寫下留言", "Write")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Content)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Email)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Content)
        </td>
        <td>
           
            @Html.ActionLink("顯示留言", "Details", new { id=item.Id }) 
           
        </td>
    </tr>
}

</table>

顯示留言頁面也稍微做個更改:

@model GuestBook.Models.Guestbook

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Guestbook</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Name)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Email)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Email)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Content)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Content)
        </dd>

    </dl>
</div>
<p>
   
    @Html.ActionLink("回到留言列表", "Index")
</p>

好了,運行程序,這個留言板已經基本可以滿足我們的要求了。它并不完美,但它對初學者來說,是一次非常不錯的開發入門之旅。

從下一章開始,我們將入門再入得深一點點,開發一個簡單商城網站實例,謝謝您的支持。轉帖的時候請把涼風有興或者AlexZeng.net進行署名。本文版權聲明:自由轉載-非商用-非衍生-保持署名(創意共享3.0許可證

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容