ASP.NET MVC3手把手教你構建Web_實用技巧

來源:互聯網
上載者:User

開發工具:VS2010+MSSQL2005,需要使用MVC3.0

環境配置

第一步:到官方網站下載MVC3,提供了簡體中文。先安裝 AspNetMVC3ToolsUpdateSetup.exe,然後安裝AspNetMVC3ToolsUpdateVS11Setup.exe

http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=1491

第二步:建立資料庫,建立測試表。然後往表裡insert些測試資料

USE [yanComdb] GO /****** 對象: Table [dbo].[NewsEntity] 指令碼日期: 03/12/2012 22:03:59 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[NewsEntity](  [NId] [int] IDENTITY(1,1) NOT NULL,  [Title] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,  [Information] [text] COLLATE Chinese_PRC_CI_AS NULL,  [Time] [datetime] NOT NULL CONSTRAINT [DF_NewsEntity_Time] DEFAULT (getdate()),  CONSTRAINT [PK_NewsEntity] PRIMARY KEY CLUSTERED (  [NId] ASC )WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

構建列表頁面

第一步:開啟VS,建立選擇MVC3 web應用程式,輸入項目名稱以及目錄

第二步:建立NewsEntity類,本文使用自己手寫實體類(沒有使用LinqtoSql,EF等orm)

[TableAttribute("NewsEntity")]//這行很重要,因為mvc架構預設去db中找類名複數的表名  public class NewsEntity  {   [Key]//設定主鍵   public int NId { get; set; }    [StringLength(100)]//設定驗證資訊   [Required(ErrorMessage="標題不可為空")]   [DisplayName("標題")]   public string Title { get; set; }    [Required(ErrorMessage = "本文必須填寫")]   [DisplayName("本文")]   public string Information { get; set; }    public DateTime Time { get; set; }  } 

第三步:設定資料庫串連字元,注意此處的name對應下一步中建立的類名。

<connectionStrings> <add name="ProjectEntity" connectionString="Data Source=ip;Initial Catalog=yanComdb;Persist Security Info=True;User ID=;Password=" providerName="System.Data.SqlClient" /> </connectionStrings> 

第四步:建立ProjectEntity類,需要繼承DbContext

public class ProjectEntity : DbContext  {   public DbSet<NewsEntity> NewsEntity { get; set; }  } 

第五步:建立Controller,

ProjectEntity PE = new ProjectEntity();   public ActionResult News()   {    try    {     var list = PE.NewsEntity.ToList();     return View(list);    }    catch (Exception e)    {     throw e;    }   } 

第六步:在News上右鍵,建立視圖。勾選“建立強型別視圖”,選擇NewsEntity,支架模組選擇List


添加後,cshtml代碼如下:

@model IEnumerable<TaiQiu.Models.NewsEntity> @{  ViewBag.Title = "後台新聞管理列表";  Layout = "~/Views/Shared/_MLayout.cshtml"; } <h2>  新聞列表</h2> <p>  @Html.ActionLink("添加", "Create") </p> <table>  <tr>   <th width="50px">    ID   </th>   <th width="300px">    標題   </th>   <th width="150px">    時間   </th>   <th>   </th>  </tr>  @foreach (var item in Model)  {   <tr>    <td>     @Html.DisplayFor(modelItem => item.NId)    </td>    <td>     @Html.DisplayFor(modelItem => item.Title)    </td>    <td>     @Html.DisplayFor(modelItem => item.Time)    </td>    <td>     @Html.ActionLink("編輯", "EditNews", new { id = item.NId }) |     @Html.ActionLink("刪除", "DeleteNews", new { id=item.NId })    </td>   </tr>  } </table> 

運行後效果圖如下:


到此,第一個列表頁面就完成了(未涉及分頁,後續會更新)。關於添加,修改,刪除也就很容易了。

添加Controller代碼:

[HttpPost]   [ValidateInput(false)]   public ActionResult Create(NewsEntity news)   {    if (ModelState.IsValid)    {     news.Time = DateTime.Now;     PE.NewsEntity.Add(news);     try     {      PE.SaveChanges();      return RedirectToAction("News");     }     catch (Exception e)     {      throw e;     }     }    return View();   } 

添加頁面:

@model TaiQiu.Models.NewsEntity @{  ViewBag.Title = "添加新聞";  Layout = "~/Views/Shared/_MLayout.cshtml"; } <h2>  添加新聞</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/kindeditor/kindeditor.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/kindeditor/lang/zh_CN.js")" type="text/javascript"></script> <script type="text/javascript">   var editor;   KindEditor.ready(function (K) {    editor = K.create('textarea[name="Information"]', {     allowFileManager: true    });   }); </script> @using (Html.BeginForm()) {  @Html.ValidationSummary(true)  <fieldset>   <legend>News</legend>   <div class="editor-label">    @Html.LabelFor(model => model.Title)   </div>   <div class="editor-field">    @Html.TextBoxFor(model => model.Title, new { style = "width:500px" })    @Html.ValidationMessageFor(model => model.Title)   </div>   <div class="editor-label">    @Html.LabelFor(model => model.Information)   </div>   <div class="editor-field">    @Html.TextAreaFor(model => model.Information, new { style="width:800px;height:400px"})    @Html.ValidationMessageFor(model => model.Information)   </div>   <p>    <input type="submit" value="Create" />   </p>  </fieldset> } <div>  @Html.ActionLink("返回列表", "Index") </div> 

修改頁面一樣,Controller稍微有點修改:

[HttpPost]   [ValidateInput(false)]   public ActionResult EditNews(NewsEntity news)   {    if (ModelState.IsValid)    {     news.Time = DateTime.Now;     PE.Entry(news).State = EntityState.Modified;//修改     PE.SaveChanges();     return RedirectToAction("News");    }    return View(news);   } 

刪除Controller代碼:

public ActionResult DeleteNews(int id)   {    var model = PE.NewsEntity.Find(id);    PE.NewsEntity.Remove(model);    PE.SaveChanges();    return RedirectToAction("News");   } 

小編剛接觸MVC3,本文也只是本人學習中的一點點積累,有很多不好的地方,希望大家多提意思。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.