Asp.net MVC 实例

http://www.cnblogs.com/chrischen662/archive/2010/08/13/1798876.html

MVC架构已深得人心,微软也不甘落后,推出了Asp.net MVC,并在vs2010中已经内置了MVC的相关功能。如果使用vs2008,需要下载安装Service Pack 1和ASP.NET MVC Framework。MVC现在已经是2.0的版本。

选择相关开发语言,创建一个 ASP.NET MVC Web Application 项目,选择不需要单元测试,这样生成了一个MVC框架,按Ctrl+F5运行,可看到一个欢迎主页。

注意:使用MVC后不是按链接文件来访问页面,而是通过控制器实现路由链接。

我们通过一个简单的增删查改的功能来体会一下MVC开发的过程。

第一步:模块开发

首先我们创建一个简单的表格:test,该表格只有两个字段:id和name。并创建一个数据类,在Models文件夹中创建一个类,代码如下:

代码

//Test.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;



namespace MvcWeb.Models

{

public class Test

{

private int _id = -1;



public int id

{

get { return _id; }

set { _id = value; }

}



public String name {get;set;}

}

}

然后在Models文件夹中创建一个文件夹:Maping,在此文件中新建一个LINQ to Sql,将test表拖进设计器中,保存。

最后在Models文件夹中新建一个类:TestModel.cs,输入如下代码:

代码

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Data.Linq;

using MvcWeb.Models.Maping;



namespace MvcWeb.Models

{

public static class TestModel

{

private static TestDbMapingDataContext testDb = new TestDbMapingDataContext();



//返回记录总数

public static int Count()

{

return testDb.test.Count();

}



//分页列表

public static List<Test> GetList(int page, int pageSize)

{

var query = (from c in testDb.test orderby c.id ascending select c).Skip((page - 1) * pageSize).Take(pageSize);

List<Test> result = new List<Test>();

foreach (var t in query)

result.Add(FillRecord(t));

return result;

}



//列表

public static List<Test> GetList()

{

var query = (from c in testDb.test orderby c.id ascending select c);

List<Test> result = new List<Test>();

foreach (var t in query)

result.Add(FillRecord(t));

return result;

}



//修改和插入保存

public static long Save(Test myTest)

{

try

{

test t = (from c in testDb.test where c.id == myTest.id select c).FirstOrDefault();

if (t == null)

{

t = new test();

t.id = myTest.id;

t.name = myTest.name;

testDb.test.InsertOnSubmit(t);

}

else

{

t.name = myTest.name;

}

testDb.SubmitChanges();

return t.id;

}

catch(ChangeConflictException ce)

{

testDb.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);

testDb.SubmitChanges();

}

return -1;

}



//删除记录

public static bool Delete(int id)

{

try

{



test t = (from c in testDb.test where c.id == id select c).FirstOrDefault();

testDb.test.DeleteOnSubmit(t);



testDb.SubmitChanges();

return t != null;

}

catch (ChangeConflictException ce)

{

testDb.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);

testDb.SubmitChanges();

}

return false;

}



//取一条记录

public static Test GetItem(int id)

{

test t = (from c in testDb.test where c.id == id select c).FirstOrDefault();

return FillRecord(t);

}



//构造数据对象

private static Test FillRecord(test i)

{

Test result = null;

if (i != null)

{

result = new Test();

result.id = i.id;

result.name = i.name;

}

return result;

}

}

}

第二步:控制器开发

在Controllers文件夹中右键选择Controller,将生成一个控制器,将文件名改为:TestController.cs,并将代码做些修改,以访问模块:

代码

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using MvcWeb.Models;



namespace MvcWeb.Controllers

{

public class TestController : Controller

{

//

// GET: /Test/

int pageSize = 3;



public ActionResult Index(int page)

{

if (page * pageSize > TestModel.Count()) page = page - 1;

if (page <= 0) page = 1;



ViewData["page"] = page;



var model = TestModel.GetList(page, pageSize);



return View(model);

}



//

// GET: /Test/Details/5



public ActionResult Details(int id)

{

var model = TestModel.GetItem(id);

return View(model);

}



//

// GET: /Test/Create



public ActionResult Create()

{

Test mytest = new Test();

return View(mytest);

}



//

// POST: /Test/Create



[HttpPost]

public ActionResult Create(int id,FormCollection collection)

{

try

{

// TODO: Add insert logic here

Test mytest = new Test();

UpdateModel(mytest, collection.ToValueProvider());

if(mytest.name == null)

ViewData.ModelState.AddModelError("name", "userName not specified.");

if (!ViewData.ModelState.IsValid)

throw new InvalidOperationException();

TestModel.Save(mytest);



return RedirectToAction("Index?page=1");



}

catch(InvalidOperationException ex)

{

return View(new Test());

}

}



//

// GET: /Test/Edit/5



public ActionResult Edit(int id)

{

var model = TestModel.GetItem(id);

return View(model);

}



//

// POST: /Test/Edit/5



[HttpPost]

public ActionResult Edit(int id, FormCollection collection)

{

try

{

// TODO: Add update logic here

Test mytest = new Test();



UpdateModel(mytest, collection.ToValueProvider());



TestModel.Save(mytest);



return RedirectToAction("Index?page=1");

}

catch

{

return View();

}

}



//

// GET: /Test/Delete/5



public ActionResult Delete(int id)

{

var model = TestModel.GetItem(id);

return View(model);

}



//

// POST: /Test/Delete/5



[HttpPost]

public ActionResult Delete(int id, FormCollection collection)

{

try

{

// TODO: Add delete logic here

TestModel.Delete(id);

return RedirectToAction("Index", new { page = 1 });

}

catch

{

return View();

}

}

}

}

第三步:视图开发

在控制器的Index方法中按右键,选择“Add View”,作出如下图的选择:

即在Views/Test文件夹下面生成一个视图:Index.aspx,因为我们使用了分页设计,所以在文件后面加上如代码:

<%= Html.ActionLink("Create New", "Create") %>

<% =Html.ActionLink("<< 前一页", "Index", new { page = (int)ViewData["Page"] - 1 })%>

<% =Html.ActionLink("后一页 >>", "Index", new { page = (int)ViewData["Page"] + 1 })%>

打开Views/Home/Index.aspx,加入一个对Test页面的链接:

<%= Html.ActionLink("测试", "Index?page=1", "Test")%>

按上面的方法在控制器的Create, Edit, Delete生成相关视图,因为主页使用了分页,所以要将返回主页的链接“Back to List”,略作修改:“Index?page=1”。我们可以看看生成的Create.aspx的代码:

代码

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcWeb.Models.Test>" %>



<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">

Create

</asp:Content>



<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">



<h2>Create</h2>



<% using (Html.BeginForm()) {%>

<%= Html.ValidationSummary(true) %>



<fieldset>

<legend>Fields</legend>



<div class="editor-label">

<%= Html.LabelFor(model => model.id) %>

</div>

<div class="editor-field">

<%= Html.TextBoxFor(model => model.id) %>

<%= Html.ValidationMessageFor(model => model.id) %>

</div>



<div class="editor-label">

<%= Html.LabelFor(model => model.name) %>

</div>

<div class="editor-field">

<%= Html.TextBoxFor(model => model.name) %>

<%= Html.ValidationMessageFor(model => model.name) %>

</div>



<p>

<input type="submit" value="Create" />

</p>

</fieldset>



<% } %>



<div>

<%= Html.ActionLink("Back to List", "Index?page=1") %>

</div>



</asp:Content>


完成任务,按Ctrl+F5运行,在主页上点击“测试”,即可体验增删查改的功能。

原文地址:https://www.cnblogs.com/blsong/p/1945563.html