zoukankan      html  css  js  c++  java
  • asp.net mvc(一)

        这些天开始学习asp.net mvc,用传统的asp.net已经快四的年了,刚开始接触asp.net mvc确认感觉有点不适应,主要体现在asp.net mvc的实现上。

        问题一:要想学习asp.net mvc,我个人觉的最重要的一步是知道mvc路由机制,传统的asp.net程序要想访问一个页面,都是根据页面路径来访问,但MVC并不能直接访问aspx页面。

        问题二:理解MVC三部分的含义和用法。当我们创建一个asp.net mvc应用程序时,系统会默认生成三个文件夹: 
                   1:Controllers,对应MVC中的C,主要是处理所有请求与做出对应的响应;  
                   2:Models,对应MVC中的M,相当时我们平时创建工程中的实体工程,只不过在MVC中它充当了存放数据模型的作用;
                   3:Views,对应MVC中的V,这里就是存放用户访问的页面文件,但是这个文件不能在浏览器中根据路径访问。
        对于系统生成的asp.net mvc项目,我对其做了如下扩展:

        扩展点一:系统之所以在web工程中直接创建了三个文件夹,是为了更加直观的体现MVC模式,真正项目中我们需要把它们分开。

        扩展点二:MVC中重要的路由处理,默认情况是在Global.asax文件中,我们也可以把这块内容独立出来。

        扩展点三:把Controller类和业务逻辑分离,这里可以采用Repository模式。

        案例DEMO:创建一个简单的留言簿的项目,数据存储采用sql,本想用linq to entity,但总觉的这部分还相关不完善,且性能存在问题,故使用传统ado.net实现数据存储。下面是这个项目的分层。

        1:GuestBook.Web,页面表示层  ,MVC中的V。

        2:GuestBook.MVC.Controller,存放项目所有的Controller,MVC中的C。我们知道Controller有两个作用:第一,处理请求;第二,做出对应的响应。第二点就是我们平时理解的后台功能实现,例如数据的增删改查等。我们可以把这部分功能与Controller分离,即所有的业务逻辑都写在业务逻辑层,不直接依赖Controller,我们可以进一步把这些功能点抽象出来,让Controller依赖一个公共的接口。这个思想我之前的一篇文章有点异曲同工之处:对增删改查用面向对象进行包装

          首先:创建一个Repository接口:IRepository.cs,里面包含些常见数据处理操作方法:这个接口是一个泛型接口,以实现所有实体类的通用性。

    public interface IRepository<T>
        {
            List
    <T> FindAllInfo();
            T GetInfo(T model);
            
    bool  Add(T model);
            
    bool  Delete(T model);
            
    bool  Edit(T model);
        }

       
         然后:实现一条留言的数据处理:

    public List<GuestBookInfo> FindAllInfo()
            {
                
    string sql = "select * from GuestBook";
               
                List
    <GuestBookInfo> list = new List<GuestBookInfo>();
                
    using(SqlDataReader dr=SqlHelper .ExecuteReader (conn ,CommandType .Text ,sql ))
                {
                    
    while  (dr.Read())
                    {
                        GuestBookInfo model 
    = new GuestBookInfo();
                        model.ID 
    = int.Parse (dr["ID"].ToString());
                        model.sTitle 
    = dr["sTitle"].ToString();
                        model.sContent 
    = dr["sContent"].ToString();
                        list.Add(model);
                    }

                }
                
    return list  ;
            }
            
    public GuestBookInfo GetInfo(GuestBookInfo model)
            {
                
    string sql = "select * from GuestBook where ID="+model.ID .ToString ();
                
    using (SqlDataReader dr = SqlHelper.ExecuteReader(conn, CommandType.Text, sql))
                {
                    
    if (dr.Read())
                    {
                        model.ID 
    = int.Parse(dr["ID"].ToString());
                        model.sTitle 
    = dr["sTitle"].ToString();
                        model.sContent 
    = dr["sContent"].ToString();
                        
                    }

                }
                
    return model ;
            }
            
    public bool Add(GuestBookInfo model)
            {
                
    string sql = "insert into GuestBook (sTitle,sContent) values ('" + model.sTitle + "','" + model.sContent + "')";
                
    int i = SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                
    if (i > 0)
                { 
    return true; }
                
    return false ;
            }
            
    public bool Delete(GuestBookInfo model)
            {
                
    string sql = "delete GuestBook where ID=" + model.ID.ToString();
                
    int i = SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                
    if (i > 0)
                { 
    return true; }
                
    return false;
            }
            
    public bool Edit(GuestBookInfo model)
            {
                
    string sql = "update GuestBook set sTitle='" + model.sTitle + "',sContent='" + model.sContent + "' where ID=" + model.ID.ToString();
                
    int i = SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                
    if (i > 0)
                { 
    return true; }
                
    return false;
            }

          
          其实:Controller依赖IRepository接口。
            

    public class GuestBookController : System.Web.Mvc.Controller
        {
            IRepository
    <GuestBookInfo> inter = new BLL_GuestBook();
            
    public ActionResult Index()
            {
                var models 
    = inter.FindAllInfo();
                
    return View("Index", models);
            }
           [AcceptVerbs(HttpVerbs.Post)]
           
    public ActionResult Create(GuestBookInfo model)
           {
               
               inter.Add(model );
               
    return RedirectToAction("Index");
           }   
           
    public ActionResult Create()
           {
               GuestBookInfo model 
    = new GuestBookInfo();        
               
    return View(model );
           }
           
    public ActionResult Details(int id)
           {
               
               GuestBookInfo model
    =new GuestBookInfo ();
               model .ID 
    =id;
               model 
    =inter.GetInfo (model );
               
    if (string .IsNullOrEmpty (model.sTitle ))
               { 
    return View("NotFound"); }
               
    else
               {
                   
    return View("Details",model );
               }
           }
           
    public ActionResult Edit(int id)
           {
               GuestBookInfo model 
    = new GuestBookInfo();
               model.ID 
    = id;
               model 
    = inter.GetInfo(model);
               
    if (string.IsNullOrEmpty(model.sTitle))
               { 
    return View("NotFound"); }
               
    else
               {
                   
    return View("Edit", model);
               }
           }
           [AcceptVerbs(HttpVerbs.Post)]
           
    public ActionResult Edit(int id, FormCollection formValues)
           {
               GuestBookInfo model 
    = new GuestBookInfo();
               model.ID 
    = id;
               model 
    = inter.GetInfo(model);
               UpdateModel(model );
               inter.Edit(model);
               
    return RedirectToAction("Index");
           }
           
    public ActionResult Delete(int id)
           {
               GuestBookInfo model 
    = new GuestBookInfo();
               model.ID 
    = id;
               model 
    = inter.GetInfo(model);
               
    if (model == null)
                   
    return View("NotFound");
               inter.Delete(model);
               
    return RedirectToAction("Index");
           }

        }

       
        3:GuestBook.Model,MVC中的M。

        4:GuestBook.RouteManager,路由管理项目,把路由处理从Global.asax中分离开。我们创建一个新类:MyMvcAppliation.cs

    public  class MyMvcAppliation: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 string[] { "GuestBook.MVC.Controller" }
                );
               

            }

            
    protected void Application_Start()
            {
                ControllerBuilder.Current.DefaultNamespaces.Add(
    "GuestBook.MVC.Controller");
                RegisterRoutes(RouteTable.Routes);
            }
        }

        5:GuestBook.Data,数据处理工具类,例如SqlHelp等等。

        6:GuestBook.DAL,数据处理层。

        7:GuestBook.BLL,业务逻辑层。

        8:GuestBook.MyInterface,相关接口,本项目中包含Repository模式中的接口类。

         这篇文章主要是探讨了MVC项目的分层以及部分扩展,欢迎大家提出更好的想法,在后面的文章中,我会总结点MVC与传统asp.net不同点,这样理解asp.net mvc就不那么麻烦了。

  • 相关阅读:
    CSS进阶-深入理解vertical-align和line-height的关系
    困难的串【转】
    【转】常用 Git 命令清单
    程序员常用等宽字体
    IE的特有属性hasLayout和BFC
    css深入理解之行高line-height
    mysql 索引优化,不走索引的原因
    php解决高并发(文件锁)
    mysql索引详解
    http错误代码
  • 原文地址:https://www.cnblogs.com/ASPNET2008/p/1535534.html
Copyright © 2011-2022 走看看