關於ASP.NETMVC入門學習(一)


 

一、MVC模式

MVC(Model-View-Controller,模型—視圖—控制器模式)用於表示一種軟件架構模式。它
把軟件系統分為三個基本部分:模型(Model),視圖(View)和控制器(Controller)。

二、創建MVC項目

  這里使用的是VS 2017

  1.新建項目

  選擇ASP.NET Web應用程序

  

 

  選擇MVC

  

 

  項目創建后的大致內容如下:

  

 

   App_Data :這個目錄跟一般的 ASP.NET website 是一樣的,用於存放數據。

   Content :這個目錄是建議用來存放一下資源文件的。例如 CSS、JS、圖片等等。當然不願 意的話,完全可以不放到這里來。

   Controllers :這個目錄是建議將 Controller 類都放到這里來,方便管理。Controller 類的命名 必須以 Controller 結尾,例如一個名為 Home 的 Controller 則要命名為 HomeController。

  Models :這個目錄是建議用來存放的業務實體、數據訪問層代碼的類的。當然,更好的做 法覺得應該是將 Models 獨立為一個類庫。

  Views :在默認情況下,所有的 view 文件都必須放到這個目錄下來,每一個 Controller 對應 一個子目錄,而且子目錄的命名必須以 Controller 的命名一樣。例如,HomeController 的 view 就應該放到 Home 子目錄中。見到 Views 目錄下還有一個 Shared 的子目錄,這個子目錄是 用於存放一些共享的 view 的,例如 Error.aspx 和 Site.Master 。 Controller 在 Views\ControllerNmae 中找不到指定的 view 的時候,會到 Shared 中去尋找。 

  下面來看一下 ASP.NET MVC 比較核心的 DLL:

    

 

  System.Web.Routing :URL 路由。將一個 URL 路由到對應的 Controller 上靠的就是這個。 是在 HttpModule 里面處理的。

  System.Web.Extensions :這個是 ASP.NET AJAX 的。 System.Web.Mvc: ASP.NET MVC 最主要的程序集。在 CodePlex 上放出源代碼的就是這個 DLL。

  System.Web.Abstractions :這個程序集是一些相關的基類來的。例如 HttpContextBase、 HttpRequestBase 等等。

 

 

三、關於建立學生表的信息

  新建數據庫並建表,字段如圖所示。

  

 

 

  創建數據模式類

  在Models文件中右鍵選擇“添加”——“類”,命名為:Student

  

 

 

輸入如下代碼:

 1     public class Student
 2     {
 3         [Key]
 4         [Required(ErrorMessage = "不能為空")]
 5         [Display(Name ="學號")]
 6         public string Sno { get; set; }
 7 
 8         [Required(ErrorMessage = "不能為空")]
 9         [Display(Name = "姓名")]
10         public string Sname { get; set; }
11 
12         [Required(ErrorMessage = "不能為空")]
13         [Display(Name = "性別")]
14         public string Sex { get; set; }
15 
16         [Required(ErrorMessage = "不能為空")]
17         [Display(Name = "QQ")]
18         public string SQQ { get; set; }
19 
20         [Required(ErrorMessage = "不能為空")]
21         [Display(Name = "宿舍")]
22         public string Sdormitory { get; set; }
23 
24     }
25 
26     public class studentDBContext : DbContext
27     {
28         [Key]
29         public DbSet<T_student> students { get; set; }
30     }

   在添加數據庫上下文類時會遇到問題

 using System.Data.Entity;

  public class studentDBContext : DbContext
    {
        public DbSet<Student> students { get; set; }
    }

 這里可能會添加失敗,這是由於沒有添加EF(EntityFramework)的NuGet程序包

 這是添加的方法:

  工具——>NuGet包管理器——>程序包管理器控制台——>輸入“Install-Package EntityFramework”

  或者在解決方案下的項目的引用中選擇“NuGet程序包”,然后在瀏覽中輸入“EntityFramework”並下載即可。

 

 連接數據庫

點擊"服務器資源管理器" ,右鍵數據連接 添加連接。然后選好服務器名,數據庫名點 擊"確定"按鈕。然后查看屬性,這里有連接字符串。

 

 打開項目Web.config文件

 

 

在這里添加連接字串

 

 

具體如下:

  <connectionStrings>
    <add name="studentDBContext" connectionString="Data Source=.;Initial Catalog=Student_data;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient"/>
  </connectionStrings>

 

編寫 Controller  :在項目中找到"Controllers"文件夾右擊,單擊"添加" 再單擊菜單"Controller…",按下圖 填寫: 
 

 

 

點擊Index()添加視圖

 

 

 視圖類型使用模板

 

 視圖代碼:

 1 @model IEnumerable<MVC_test.Models.Student>
 2 
 3 @{
 4     ViewBag.Title = "Index";
 5 }
 6 
 7 <h2>Index</h2>
 8 
 9 <p>
10     @Html.ActionLink("Create New", "Create")
11 </p>
12 <table class="table">
13     <tr>
14         <th>
15             @Html.DisplayNameFor(model => model.Sname)
16         </th>
17         <th>
18             @Html.DisplayNameFor(model => model.Sex)
19         </th>
20         <th>
21             @Html.DisplayNameFor(model => model.SQQ)
22         </th>
23         <th>
24             @Html.DisplayNameFor(model => model.Sdormitory)
25         </th>
26         <th></th>
27     </tr>
28 
29 @foreach (var item in Model) {
30     <tr>
31         <td>
32             @Html.DisplayFor(modelItem => item.Sname)
33         </td>
34         <td>
35             @Html.DisplayFor(modelItem => item.Sex)
36         </td>
37         <td>
38             @Html.DisplayFor(modelItem => item.SQQ)
39         </td>
40         <td>
41             @Html.DisplayFor(modelItem => item.Sdormitory)
42         </td>
43         <td>
44             @Html.ActionLink("Edit", "Edit", new { id=item.Sno }) |
45             @Html.ActionLink("Details", "Details", new { id=item.Sno }) |
46             @Html.ActionLink("Delete", "Delete", new { id=item.Sno })
47         </td>
48     </tr>
49 }
50 
51 </table>

 

視圖添加后運行

 

 

 添加創建,編輯,刪除

代碼如下:

 public class StudentController : Controller
    {
        //創建數據庫連接對象
        private studentDBContext db = new studentDBContext();
        // GET: Student
        public ActionResult Index()
        {
            return View(db.students.ToList());
        }

        //創建
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(T_student s)
        {
            db.students.Add(s);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        
        //編輯
        public ActionResult Edit(string id)
        {
            T_student s = db.students.Find(id);//查找給定的實體
            if (s==null)
            {
                return HttpNotFound();
            }
            return View(s);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(T_student s)
        {
            if(ModelState.IsValid)
            {
                db.Entry(s).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(s);
        }
        //刪除
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            T_student s = db.students.Find(id);
            if (s == null)
            {
                return HttpNotFound();
            }
            return View(s);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ActionName("Delete")]       
        public ActionResult Deletel(string id)
        {
            T_student s = db.students.Find(id);

            db.students.Remove(s);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            T_student s = db.students.Find(id);
            if (s == null)
            {
                return HttpNotFound();
            }
            return View(s);
        }
    }  

並創建相應的視圖

創建視圖

 

 編輯視圖

 

 

刪除視圖

 

 

明細視圖:

 

 

 創建視圖代碼:

@model MVC_test.Models.Student

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


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

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

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

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

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

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

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

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

編輯視圖代碼:

@model MVC_test.Models.Student

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

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

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

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

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

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

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

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

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

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Sno }) |
    @Html.ActionLink("Back to List", "Index")
</p>

刪除代碼:

@model MVC_test.Models.Student

@{
    ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Student</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Sname)
        </dt>

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

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

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

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

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

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

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

    </dl>

    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()

        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }
</div>

 

明細視圖代碼:

@model MVC_test.Models.Student

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

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

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

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

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

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

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

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

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

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Sno }) |
    @Html.ActionLink("Back to List", "Index")
</p>

 

 

創建的視圖均套用MVC中的模板,也可以自己手動編寫(比較麻煩,容易出錯)。

在StudentController.cs中編寫代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using MVC_test.Models;
using System.Net;

namespace MVC_test.Controllers
{
    public class StudentController : Controller
    {   
        //創建數據庫連接對象
        private studentDBContext db = new studentDBContext();
        // GET: Student
        public ActionResult Index()
        {
            return View(db.students.ToList());
        }
        //創建
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(Student s)
        {
            db.students.Add(s);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        //編輯
        public ActionResult Edit(string id)
        {
            Student s = db.students.Find(id);//查找給定的實體
            if (s == null)
            {
                return HttpNotFound();
            }
            return View(s);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Student s)
        {
            if (ModelState.IsValid)
            {
                db.Entry(s).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(s);
        }
        //刪除
        public ActionResult Delete(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student s = db.students.Find(id);
            if (s == null)
            {
                return HttpNotFound();
            }
            return View(s);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ActionName("Delete")]
        public ActionResult Deletel(string id)
        {
            Student s = db.students.Find(id);

            db.students.Remove(s);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student s = db.students.Find(id);
            if (s == null)
            {
                return HttpNotFound();
            }
            return View(s);
        }
    }
}

運行項目

 

 

 

 

 

 

編輯操作(對可編輯的屬性修改)

 

 

明細

 

 刪除:

 

 

增刪改查都一樣正常。

 

 

     MVC模式工作流程

這是MVC的一個簡單利用,也是初步入門學習的一個實例。主要是理解了工作流程,就能很好的理解MVC和對實例的學習。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM