Asp.net MVC 实例

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文件夹中创建一个类,代码如下:

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
// 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,输入如下代码:

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
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,并将代码做些修改,以访问模块:

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
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”,作出如下图的选择:

 2010081312061949.jpg

即在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的代码:

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
<% @ 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/chrischen662/archive/2010/08/13/1798876.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的ASP.NET MVC项目实例,用于展示如何创建一个基本的待办事项列表应用程序: 1. 首先,创建一个新的ASP.NET MVC项目。 2. 在项目中创建一个名为"TodoItem"的模型类,定义待办事项的属性,如ID、标题、描述和完成状态。 ```csharp public class TodoItem { public int ID { get; set; } public string Title { get; set; } public string Description { get; set; } public bool IsCompleted { get; set; } } ``` 3. 创建一个名为"TodoController"的控制器,用于处理与待办事项相关的操作。 ```csharp public class TodoController : Controller { private List<TodoItem> todoList = new List<TodoItem>(); public TodoController() { // 初始化一些示例数据 todoList.Add(new TodoItem { ID = 1, Title = "任务1", Description = "完成任务1", IsCompleted = false }); todoList.Add(new TodoItem { ID = 2, Title = "任务2", Description = "完成任务2", IsCompleted = true }); } public ActionResult Index() { return View(todoList); } } ``` 4. 创建一个名为"Index.cshtml"的视图,用于显示待办事项列表。 ```html @model List<TodoItem> <h2>待办事项列表</h2> <ul> @foreach (var todo in Model) { <li> <strong>@todo.Title</strong> <p>@todo.Description</p> <p>完成状态: @todo.IsCompleted</p> </li> } </ul> ``` 5. 运行项目,访问"Todo/Index"路径,即可看到待办事项列表的展示。 这只是一个简单的示例,实际的ASP.NET MVC项目可能包含更多功能和页面。通过模型、视图和控制器的结合使用,我们可以构建出更复杂和功能丰富的应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值