使用MVC框架中要注意的问题(二):将Model和Controller单独用一个项目设计

这个问题很多朋友都会问到,MVC让分工协作成为了可能。但如果所有代码和页面都在一个项目中的话,那么分工就会受到限制。其实,Model和Controller都可以单独用一个(或者多个)程序单独来做。

1. Model

Model主要负责数据读写。现在我们一般可以直接用LINQ TO SQL类型或者Entity Framework 模型来做。

严格来说,Model也分为两个部分,一个是业务实体定义(这是需要与View共享的),一个是针对业务实体的操作。只不过,上面提到的两种做法将他们合二为一了。

Model项目单独做好之后,只要在MVC Web Application中添加引用即可。很简单,也很自然。

 

2. Controller

相对来说这就稍微复杂一些。请遵循下面的规范

  • Controller的名字要满足规范,例如BlogController。Blog是Controller的名字,而Controller是后缀。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web.Mvc;

namespace MyControllers
{
    public class BlogController:Controller
    {

        public ActionResult Index() {
            return View();
        }
    }
}
  • 在global.asax文件中添加命名空间的注册,让MVC引擎知道如何查找Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication2
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" },  // Parameter defaults
                new[] {"MyControllers"}
            );

        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
}
image 
posted @ 2009-12-27 20:45  陈希章  阅读(2520)  评论(0编辑  收藏  举报