您的位置:首页 > asp.net > MVC >

ASP.NET MVC3 从零开始一步步构建Web

2012-04-16 20:51 来源:未知编辑:admin点击:

微软更新速度一直都是很快,目前MVC4.0Beta已经发布了,而我还在刚刚起步MVC3.0。本文是MVC的基础,构建最简单的MVC项目。以后会陆续发布更新。

开发工具:VS2010+MSSQL2005,需要使用MVC3.0

环境配置

第一步:到官方网站下载MVC3,提供了简体中文。先安装 AspNetMVC3ToolsUpdateSetup.exe,然后安装AspNetMVC3ToolsUpdateVS11Setup.exe http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=1491

 

 

第二步:新建数据库,创建测试表。然后往表里insert些测试数据


  1. USE [yanComdb]
  2. GO
  3. /****** 对象: Table [dbo].[NewsEntity] 脚本日期: 03/12/2012 22:03:59 ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. CREATE TABLE [dbo].[NewsEntity](
  9. [NId] [int] IDENTITY(1,1) NOT NULL,
  10. [Title] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NOT NULL,
  11. [Information] [text] COLLATE Chinese_PRC_CI_AS NULL,
  12. [Time] [datetime] NOT NULL CONSTRAINT [DF_NewsEntity_Time] DEFAULT (getdate()),
  13. CONSTRAINT [PK_NewsEntity] PRIMARY KEY CLUSTERED
  14. (
  15. [NId] ASC
  16. )WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
  17. ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

构建列表页面

第一步:打开VS,新建选择MVC3 web应用程序,输入项目名称以及目录

 

 

 

 

第二步:创建NewsEntity类,本文使用自己手写实体类(没有使用LinqtoSql,EF等orm)


  1. [TableAttribute("NewsEntity")]//这行很重要,因为mvc框架默认去db中找类名复数的表名
  2. public class NewsEntity
  3. {
  4. [Key]//设置主键
  5. public int NId { get; set; }
  6.  
  7. [StringLength(100)]//设置验证信息
  8. [Required(ErrorMessage="标题不能为空")]
  9. [DisplayName("标题")]
  10. public string Title { get; set; }
  11.  
  12. [Required(ErrorMessage = "正文必须填写")]
  13. [DisplayName("正文")]
  14. public string Information { get; set; }
  15.  
  16. public DateTime Time { get; set; }
  17. }

第三步:配置数据库连接字符,注意此处的name对应下一步中创建的类名。


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

第四步:创建ProjectEntity类,需要继承DbContext


  1. public class ProjectEntity : DbContext
  2. {
  3. public DbSet<NewsEntity> NewsEntity { get; set; }
  4. }

第五步:新建Controller,


  1. ProjectEntity PE = new ProjectEntity();
  2. public ActionResult News()
  3. {
  4. try
  5. {
  6. var list = PE.NewsEntity.ToList();
  7. return View(list);
  8. }
  9. catch (Exception e)
  10. {
  11. throw e;
  12. }
  13. }

第六步:在News上右键,新建视图。勾选“创建强类型视图”,选择NewsEntity,支架模块选择List

 

 

添加后,cshtml代码如下:


  1. @model IEnumerable<TaiQiu.Models.NewsEntity>
  2. @{
  3. ViewBag.Title = "后台新闻管理列表";
  4. Layout = "~/Views/Shared/_MLayout.cshtml";
  5. }
  6. <h2>
  7. 新闻列表</h2>
  8. <p>
  9. @Html.ActionLink("添加", "Create")
  10. </p>
  11. <table>
  12. <tr>
  13. <th width="50px">
  14. ID
  15. </th>
  16. <th width="300px">
  17. 标题
  18. </th>
  19. <th width="150px">
  20. 时间
  21. </th>
  22. <th>
  23. </th>
  24. </tr>
  25. @foreach (var item in Model)
  26. {
  27. <tr>
  28. <td>
  29. @Html.DisplayFor(modelItem => item.NId)
  30. </td>
  31. <td>
  32. @Html.DisplayFor(modelItem => item.Title)
  33. </td>
  34. <td>
  35. @Html.DisplayFor(modelItem => item.Time)
  36. </td>
  37. <td>
  38. @Html.ActionLink("编辑", "EditNews", new { id = item.NId }) |
  39. @Html.ActionLink("删除", "DeleteNews", new { id=item.NId })
  40. </td>
  41. </tr>
  42. }
  43. </table>

运行后效果图如下:

 

 

到此,第一个列表页面就完成了(未涉及分页,后续会更新)。关于添加,修改,删除也就很容易了。

添加Controller代码:


  1. [HttpPost]
  2. [ValidateInput(false)]
  3. public ActionResult Create(NewsEntity news)
  4. {
  5. if (ModelState.IsValid)
  6. {
  7. news.Time = DateTime.Now;
  8. PE.NewsEntity.Add(news);
  9. try
  10. {
  11. PE.SaveChanges();
  12. return RedirectToAction("News");
  13. }
  14. catch (Exception e)
  15. {
  16. throw e;
  17. }
  18.  
  19. }
  20. return View();
  21. }

添加页面:


  1. @model TaiQiu.Models.NewsEntity
  2. @{
  3. ViewBag.Title = "添加新闻";
  4. Layout = "~/Views/Shared/_MLayout.cshtml";
  5. }
  6. <h2>
  7. 添加新闻</h2>
  8. <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
  9. <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
  10. <script src="@Url.Content("~/Scripts/kindeditor/kindeditor.js")" type="text/javascript"></script>
  11. <script src="@Url.Content("~/Scripts/kindeditor/lang/zh_CN.js")" type="text/javascript"></script>
  12. <script type="text/javascript">
  13. var editor;
  14. KindEditor.ready(function (K) {
  15. editor = K.create('textarea[name="Information"]', {
  16. allowFileManager: true
  17. });
  18. });
  19. </script>
  20. @using (Html.BeginForm())
  21. {
  22. @Html.ValidationSummary(true)
  23. <fieldset>
  24. <legend>News</legend>
  25. <div class="editor-label">
  26. @Html.LabelFor(model => model.Title)
  27. </div>
  28. <div class="editor-field">
  29. @Html.TextBoxFor(model => model.Title, new { style = "width:500px" })
  30. @Html.ValidationMessageFor(model => model.Title)
  31. </div>
  32. <div class="editor-label">
  33. @Html.LabelFor(model => model.Information)
  34. </div>
  35. <div class="editor-field">
  36. @Html.TextAreaFor(model => model.Information, new { style="width:800px;height:400px"})
  37. @Html.ValidationMessageFor(model => model.Information)
  38. </div>
  39. <p>
  40. <input type="submit" value="Create" />
  41. </p>
  42. </fieldset>
  43. }
  44. <div>
  45. @Html.ActionLink("返回列表", "Index")
  46. </div>

修改页面一样,Controller稍微有点修改:


  1. [HttpPost]
  2. [ValidateInput(false)]
  3. public ActionResult EditNews(NewsEntity news)
  4. {
  5. if (ModelState.IsValid)
  6. {
  7. news.Time = DateTime.Now;
  8. PE.Entry(news).State = EntityState.Modified;//修改
  9. PE.SaveChanges();
  10. return RedirectToAction("News");
  11. }
  12. return View(news);
  13. }

删除Controller代码:


  1. public ActionResult DeleteNews(int id)
  2. {
  3. var model = PE.NewsEntity.Find(id);
  4. PE.NewsEntity.Remove(model);
  5. PE.SaveChanges();
  6. return RedirectToAction("News");
  7. }

小弟刚接触MVC3,本文也只是本人学习中的一点点积累。有很多不好的地方,希望大家多提意思。