当前位置:Gxlcms > asp.net > ASP.NET MVC3手把手教你构建Web

ASP.NET MVC3手把手教你构建Web

时间:2021-07-01 10:21:17 帮助过:43人阅读

开发工具: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,本文也只是本人学习中的一点点积累,有很多不好的地方,希望大家多提意思。

人气教程排行