mvcframeworkProgramming ASP.NET MVCFundamentals of ASP.NET MVC(四)Controller

在写这篇文章之前,xxx已经写过了几篇关于改mvcframework主题的文章,想要了解的朋友可以去翻一下之前的文章

                  在asp.net mvc的架构里,controller用来响应用户的输入,同时协调view和model以及数据访问层。contorller也是一个类,包括的方法,这些方法是在routing framework处理一个请求的时候被调用的。

                   我们可以看一下,如果我们建立程序的时候,选择InerterTemplate为我们主动生成的HomeController的代码:

    

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace InternetEBuy.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

                 我们可以看一下对应的index.cshtml

    

@{
    ViewBag.Title = "Home Page";
}
@section featured {
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1>@ViewBag.Title.</h1>     @*我们可以自己实验一下,是忽略大小写的!*@
                <h2>@ViewBag.message</h2>
            </hgroup>
            <p>
                To learn more about ASP.NET MVC visit
                <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
                The page features <mark>videos, tutorials, and samples</mark> to help you get the most from ASP.NET MVC.
                If you have any questions about ASP.NET MVC visit
                <a href="http://forums.asp.net/1146.aspx/1?MVC" title="ASP.NET MVC Forum">our forums</a>.
            </p>
        </div>
    </section>
}
<h3>We suggest the following:</h3>
<ol class="round">
    <li class="one">
        <h5>Getting Started</h5>
        ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
        enables a clean separation of concerns and that gives you full control over markup
        for enjoyable, agile development. ASP.NET MVC includes many features that enable
        fast, TDD-friendly development for creating sophisticated applications that use
        the latest web standards.
        <a href="http://go.microsoft.com/fwlink/?LinkId=245151">Learn more…</a>
    </li>

    <li class="two">
        <h5>Add NuGet packages and jump-start your coding</h5>
        NuGet makes it easy to install and update free libraries and tools.
        <a href="http://go.microsoft.com/fwlink/?LinkId=245153">Learn more…</a>
    </li>

    <li class="three">
        <h5>Find Web Hosting</h5>
        You can easily find a web hosting company that offers the right mix of features
        and price for your applications.
        <a href="http://go.microsoft.com/fwlink/?LinkId=245157">Learn more…</a>
    </li>
</ol>

                这里想说的一点就是,我上面有注释的内容,

    忽略大小写的。

                     

                    controller动作

                    我们可以看到controller类和我们在asp.net看到的.cs类没有什么区别,实际上,承当主要任务的是里头的方法(在asp.net mvc里我们把它叫做动作),它们会在处理请求时被调用。

                    举个例子,比如,我们输入 /Home/Index, routing framework就会晓得用homecontroller中的index方法来处理这个请求,然后asp.net mvc framework就会生成一个homecontroller的实例,并执行对应的index方法。接下来,Index方法就会通过ViewBag属性来把传输数据,通过view()方法,告知asp.net mvc framework 显示View目录下名称为Index的view,然后返回的actionResult类型是viewResult类型的。

    每日一道理
那蝴蝶花依然花开花落,而我心中的蝴蝶早已化作雄鹰飞向了广阔的蓝天。

                   ActionResutl

                   我们应当注意的是,controller是告知framework接下来做什么,而没有告知怎么做。关于怎么做,是最好每个action都包括的返回值来完成的。比如说,当一个controlller决议显示一个view的时候,它会通过返回一个viewresult来告知framework显示view。它本身不会渲染view,这种松耦合也是一个分离思惟的表现。

                   事实上,每一个action都应当返回一个actionresult,但是很少情况你需求手动地创立它们,只需求调用system.mvc.contorller父类提供的帮助方法,如下:

                   mvc和framework

                           从上面的列表,我们可看到,framework提供了我们须要的大部情况的返回值,当然,如果没有提供,framework也提供给我们也可以自己手工创立的能力。

                         我们也可看到,返回的类型为actionresult,这里用到了多态。还要说明一点的是,如果返回的类型在actionresult里没有找到的话,那么framework会主动将它封装成一个contentResult,然后渲染生成的内容。

                         

                          action parameter

                          事实上,action可以获得请求的信息,并通过asp.net mvc framework填充到指定的参数里,这就是asp.net mvc 里的功能强大的model binding。

                         在看model binding之前,我们还是先来看一下传统的方式。

    

public ActionResult Create()
        {
            var auction = new Models.Auction()
            {
                Title = Request["title"],
                CurrentPrice = decimal.Parse(Request["currentPrice"]),
                StartTime = DateTime.Parse(Request["startTime"]),
                EndTime = DateTime.Parse(Request["endTime"])
            };

            //return View();
        }

                     在这个create action里,要用一个请求传进来的值来实例化一个auction对象,因为auction的属性类型,有很多都不是字符串类型的,所以须要进行转换。从上面的代码,我们可以看到,这些代码其实是很“软弱的”,因为,只要其中的一个转换失败,那么这个action就会失败。当然,我们可以用tryParse方法来进行验证,但是,这就会增长很多代码,也不具有可读性。

    所以也就发生的model Binding

                        基本的model Binding

                         我们还是直接看代码:

    

public ActionResult Create(
      string title, decimal currentPrice,
      DateTime startTime, DateTime endTime
   )
{
   var auction = new Auction() {
      Title = title,
      CurrentPrice = currentPrice,
      StartTime = startTime,
      EndTime = endTime,
   };
   // ...
}

               当前的action直接把要接收的值写到了参数里,当asp.net mvc framework执行的时候,它会试图从请求里用雷同的值填充对应的参数,

    这里,我们就想到了,这里参数名称的一致就就尤为重要了。

    在里还要说明一点就是,framework不仅会查看请求对象里是否有对应的值,而且还会查看route data,query string parameter,post values,甚至是序列化的JSON对象。比如上面的代码是从一个连接字符串中获得:

                   mvc和framework

    

                  绑定庞杂对象

                  上面我们将演示直接把我们获得的值绑定到Auction对象里:

                   

public ActionResult Create(Auction auction)
{
   // ...
}

                这样是不是更加简练了,我们同时也看到了model binding的强大之处。

               

                   action filters

                  action filter帮助我们很好的解决了交差访问(存眷)的问题,通过给controller action 添加ActionFilterAttribute,来控制action执行,上面是一个阻止匿名用户访问的aciton例子:

    

[Authorize]
public ActionResult Profile()
{
    // Retrieve profile information for current user
    return View();
}

                asp.net mvc framework提供了相当多的filter来解决我们常见的一些问题,它的好处:简练、松耦合。

                    我们可以创立Action filters,通过继承 ActionFilterAttribute或者其它的asp.net mvc framework的action filter.(action filter可以很便利的给我们的网站添加用户自定义的逻辑)

               

                     

                           

文章结束给大家分享下程序员的一些笑话语录: 祝大家在以后的日子里. 男生象Oracle般健壮; 女生象win7般漂亮; 桃花运象IE中毒般频繁; 钱包如Gmail容量般壮大, 升职速度赶上微软打补丁 , 追女朋友像木马一样猖獗, 生活像重装电脑后一样幸福, 写程序敲代码和聊天一样有**。

--------------------------------- 原创文章 By
mvc和framework
---------------------------------

原文地址:https://www.cnblogs.com/xinyuyuanm/p/3112896.html