美文网首页
MVC---控制器

MVC---控制器

作者: Sombod_Y | 来源:发表于2016-12-30 23:47 被阅读0次

    <strong>一. 控制器介绍</strong>
    <strong>1.1 使用IController创建Controller</strong>
    控制器类必须实现IController接口。

        public class BasicController : IController
        {
            public void Execute(RequestContext requestContext)
            {
                string controller = (string)requestContext.RouteData.Values["controller"];
                string action = (string)requestContext.RouteData.Values["action"];
                requestContext.HttpContext.Response.Write(string.Format("Controller:{0}, Action:{1}", controller, action));
            }
        }
    

    <strong>1.2 创建派生与Controller类的控制器</strong>
    Controller类提供了三个关键特性:
    1.Action Method:不是只有一个Execute()方法,而是分解成多个方法。
    2.Action Result:返回一个描述Action结果的对象。
    3.Filter
    <strong>1.3 接收请求数据</strong>
    访问来自请求的数据共三种方法:
    1.Context上下文对象
    2.参数
    3.Model Binding
    <strong>1.3.1 通过Context获取数据</strong>

    常用的Context对象.png
            public ActionResult RenameProduct()
            {
                string userName = User.Identity.Name;
                string serverName = Server.MachineName;
                string clientIP = Request.UserHostAddress;
                DateTime dateStamp = HttpContext.Timestamp;
                string oldProductName = Request.Form["OldName"];
                string newProductName = Request.Form["NewName"];
                return View();
            }
    

    <strong>1.3.2 使用Action参数</strong>
    对于实现IController接口的Controller:

            public ActionResult ShowWeatherForecast(string city, DateTime forDate){}
    

    <strong>1.4 产生输出</strong>

     public class BasicController : IController
        {
            public void Execute(RequestContext requestContext)
            {
                string controller = (string)requestContext.RouteData.Values["controller"];
                string action = (string)requestContext.RouteData.Values["action"];
                if (action.ToLower() == "redirect")
                {
                    requestContext.HttpContext.Response.Redirect("/Derived/Index");
                }
                else
                {
                    requestContext.HttpContext.Response.Write(string.Format("Controller:{0}, Action:{1}", controller, action));
                }
            }
        }
    

    对于派生与Controller类的控制器:

     public void ProduceOutput()
            {
                if (Server.MachineName == "我的机器")
                {
                    Response.Redirect("/Basic/Index");
                } else
                {
                    Response.Write("Controller: Derived, Action: ProduceOutput");
                }
            }
    

    这些方法理论上可行,但是存在很多问题,如必须包含详细的HTML和URL结构等。
    MVC框架提供了ActionResult解决这些问题。
    <strong>1.4.1 理解ActionResult</strong>
    Action Result把“指明意图”和“执行意图”分离了。不是直接使用Response对象,而是返回一个派生于ActionResult类的对象,但这是间接发生的,不直接生成响应。

            public ActionResult ProduceOutput()
            {
                // return new RedirectResult("/Basic/Index");
                return Redirect("/Basic/Index");
            }
    

    MVC框架包含了很多内建的ActionResult类型:

    内建的ActionResult类型.png

    <strong>1.4.2 通过渲染View返回HTML</strong>

            public ActionResult Index()
            {
                return View("Homepage");// Homepage作为View的名称传递
            }
    

    <strong>1.4.3 将数据从Action传递给视图</strong>
    1.可以把一个对象作为View方法的参数发送给View:

            public ActionResult Index()
            {
                DateTime date = DateTime.Now;
                return View(date);
            }
    

    然后用Razor的Model关键字访问这个对象。

    @{ 
        ViewBag.Title = "Index";
    }
    <h2>Index</h2>
    The day is :@((DateTime)Model).DayOfWeek
    

    最好采用下面的强类型视图:

    @model DateTime
    @{
        ViewBag.Title = "Index";
    }
    <h2>Index</h2>
    the day is :@Model.DayOfWeek
    

    2.使用ViewBag传递数据

    @{
        ViewBag.Title = "Index";
    }
    <h2>Index</h2>
    the day is : @ViewBag.Date.DayOfWeek
    <p />
    The message is : @ViewBag.Message
    

    <strong>1.4.4 执行重定向</strong>
    1.重定向到字面URL(临时重定向)

            public RedirectResult Redirect()
            {
                return Redirect("/Example/Index");
            }
    

    2.重定向到路由系统的URL

            public RedirectToRouteResult Redirect()
            {
                return RedirectToRoute(new { controller = "Example", action = "Index", ID = "MyID" });
            }
    

    3.重定向到一个Action方法
    这只是对于RedirectToRoute方法的封装。

            public RedirectToRouteResult Redirect()
            {
                return RedirectToAction("Index");
            }
    

    如果只有一个参数,它假设你指向的时当前Controller的Action方法,若要重定向到另一个Controller:

                return RedirectToAction("Index", "Basic");
    

    <strong>1.4.5 返回错误及HTTP代码</strong>

            public HttpStatusCodeResult StatusCode()
            {
                return new HttpStatusCodeResult(404, "URL cannot be serviced");
                return HttpNotFound();
            }
    

    相关文章

      网友评论

          本文标题:MVC---控制器

          本文链接:https://www.haomeiwen.com/subject/eyhvvttx.html