zoukankan      html  css  js  c++  java
  • 把asp.net mvc4 controller 单独放置在一个项目实例

    一、创建一个MVC4 Web项目

    使用VS2012创建一个Web项目CommonWebSite,选择模板为MVC。这时VS2012自动添加MVC4相关的类库和模板到新的项目。如下图:

     

    二、创建一个放MVC4 Controller的类库项目

    选中解决方案添加一个类库项目CommonControllers,并要项目的根目录添加一个TestController的类文件,

    using System;

    using System.Collections.Generic;

    using System.Linq; using System.Text;

    using System.Threading.Tasks;

    using System.Web.Mvc;  //添加Using

    namespace CommonControllers.Controllers  //修改这里

    {    

      public class TestController : Controller   //继承Controller  类名跟视图保持一致这里我为视图Views下的Test文件夹创建

        {        

        public ActionResult Index()      

         {            

            ViewData["ABC"] = "Test";   

                  return View();        

          }        

        }

    }

    三、在Web项目中添加Controller类库引用

    在项目CommonWebSite中添加对项目CommonControllers引用。如下图:

    最后,在RouteConfig中注册路由是指定Controller的命名空间,如下:

     public static void RegisterRoutes(RouteCollection routes)       

      {            

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

                routes.MapRoute(                

        name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }             );        

    }

    最终查看Test/Index的结果如下图:

    四、总结

    把asp.net mvc4 controller 单独放置在一个项目有它的许多优点比如可以在多个项目中复用这些代码,易编维护等等。但是也有一些不好地方,比如不能通过右键从Controller的Action跳转到对应的视图,也不能从一个视图通过右键跳到到对应的Action方法中。具体你要根据实际情况灵活的选择。

  • 相关阅读:
    python 正则表达式
    python -- 程序异常与调试(程序调试)
    python -- 程序异常与调试(异常处理)
    python -- 程序异常与调试(识别异常)
    python -- 日期与时间
    python -- 模块与类库
    python -- 面向对象编程(继承、重写)
    python -- 面向对象编程(属性、方法)
    python -- 面向对象编程(类、对象)
    python -- 函数
  • 原文地址:https://www.cnblogs.com/mark-meng/p/6051618.html
Copyright © 2011-2022 走看看