码迷,mamicode.com
首页 > Web开发 > 详细

MVC学习笔记——控制器

时间:2016-06-15 23:57:05      阅读:350      评论:0      收藏:0      [点我收藏+]

标签:

一、创建新的控制器

操作:选中Controllers文件夹,右键Add/Controller,然后给予命名eg:StoreController

判断:一个类是否为控制器类:该类是否继承自using System.Web.Mvc.Controller

明确:模型和视图虽然非常有用,但是控制器才是真正的核心,每个请求都必须通过控制器处理,它是MVC应用程序的“指挥员”!

代码演示

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class StoreController : Controller
    {
        // GET: Store
        public string Index()
        {
            //return View();
            return "Hello from Store.Index()";
        }

        public string Browse(string genre)
        {
            string message = HttpUtility.HtmlEncode("Store.Browse,Genre=" + genre);
            return message;
        }

        public string Details()
        {
            return "Hello from Store.Details()";
        }
    }
}
View Code

 运行项目,然后浏览以下URL

/Store

/Store/Browse

/Store/Details

访问这些URL会调用控制器中的操作方法,饭后返回响应字符串,如下所示:

技术分享

技术分享

控制器操作中的参数特例:

public string Example(int id)
{
      string message = "Hello from Store.Example,num=" + id;
   return message;
}

当上述方法中参数名为id,并且数据类型为int时,ASP.NET MVC的默认路由约定就可以通过 /Store/Example/5 的方式传递参数,当然了也可以http://localhost:2261/Store/Example?id=5, 注意:参数名一定要为id,且为int

 

MVC学习笔记——控制器

标签:

原文地址:http://www.cnblogs.com/vakeynb/p/5589308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!