【引言】
小编在最近的学习中知道了mvc(Model-View-Controller),它是一种软件设计模式,相对于传统的ASP.NET Web Forms开发来说,在某些方面有了改进,在国外网站的MVC社群很活跃,互联网的红利,现在国内有越来越多的人开始了解它并接受它。
【出现原因】
为什么会出现mvc这种框架呢? 大家应该很熟悉SP.NET Web Forms这种模式的开发,经历了十年的演进,其组件化技术已经非常成熟,但是利用Web Forms开发Web应用程序还是会遇到许多瓶颈与限制,ASP.NET开发人员遇到的问题有:
- 邪恶的ViewState(用了像GridView这种超大控件就非常容易失控);
- 控件组件对HTML的控制不够直观或太过复杂;
- 不容易采用TDD(Test-driven Development)测试导向开发模式开发,也不容易撰写单元测试。
这时候mvc的优点就显现出来了:
- 清楚的关注点分离 ,强迫你写出比Web Forns 更容易维护的程序;
- 开放特性(万全开放源代码);
- 社群支持(当前国外社群非常活跃);
- 可轻易地控制HTTP的输出属性(这点比Web Forms好太多太多了);
- 优秀的开发效率;
- 易于测试的架构;
- 易于分工的架构。
MVC采用封装的思想,各层负责的事情分离,相互独立,来降低耦合度,从而使我们的系统更加的灵活,扩展性更好。
【认识它】
MVC是Model-View-Controller的缩写,中文翻译为“模式-视图-控制器”架构最早是smalltalk语言中提出的,应用于用户交互应用程序中,将交互式应用程序分为3个组件:
模型:包含核心功能和数据(核心业务逻辑)(将人机交互从核心功能中分离出来)
视图:向用户显示信息(模型对于用户来说是透明的,用户只需要观察视图)
控制器:处理用户输入(用户与模型的交互通过控制器提供的安全方法来实现)
把一个应用的输入、处理、输出流程按照Model、View、Controller的方式分离。
我们所知道的mvc……
【了解它】
1. MVC体系结构
2. MVC请求流程
【实例演示】
1. Model层写一个实体类
public class Healthytips
{
public string healthyID { get; set; }
public string healthyType { get; set; }
public string healthyContent { get; set; }
public string healthyStates { get; set; }
}
2. Controller:从视图中读取数据,向model发送数据
public class HealthyTipsController : Controller
{
//
// GET: /HealthyTips/
public ActionResult Index()
{
//返回对应视图,FrontPage为相应的cshtml的名称
return View("FrontPage");
}
public string HealthyTips()
{
HealthyTipsBLL healthytips = new HealthyTipsBLL();
return healthytips.QueryTips();
}
}
}
3. View接收和显示数据:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content ="width=device-width" />
<title>Index</title>
@*引入js文件*@
<script type="text/javascript" src="../../Content/JS/FrontPage/Index.js"></script>
</head>
<body>
……
</body>
</html>
Index.js文件
$(document).ready(function () {
$.ajax({
url: '/HealthyTips/HealthyTips',
type: 'get',
datatype: Text,
success:function(data){
var unique_id = $.gritter.add({
// (string | mandatory) the heading of the notification
title: data,
// (string | mandatory) the text inside the notification
text: 'Welcome to Dynamic Excellent System!',
// (string | optional) the image to display on the left
image: '../../Content/IMG/FrontPage/ui-sam.jpg',
// (bool | optional) if you want it to fade out on its own or just sit there
sticky: true,
// (int | optional) the time you want it to be alive for before fading out
time: '',
// (string | optional) the class name you want to apply to that specific message
class_name: 'my-sticky-class'
});
return false;
}
});
【总结】
mvc中实现了View和数据(Model)的分离、View和表现逻辑(Controller)的分离,可以有多个视图对应一个模型的能力,在需求多变的情况下,数据模型可以有多个视图的对应,增加了灵活性,减少了代码的复制,一旦数据模型发生改变,也易于维护。感谢您的阅读,期待您的宝贵意见~~