一天学会MVC3之Controllers(控制器)

一.名词解释:

      传统的WEB FORM开发是映射URL到磁盘文件,比如:"/Products.aspx" or "/Products.php"请求可能映射到:"/Products.aspx" or "/Products.php"文件

      基于MVC的方式是将请求映射到类中的方法,这一些类就叫做控制器

二.添加HomeController控制器

     HomeController用来处理我们的站点首页的请求URL

     右键点击"Controllers”文件夹
     

     

      点击添加后将创建HomeController.cs:
     
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcMusicStore.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

    }
}

下面我们修改Index方法返回一个字符串到首页修改代码如下:
 public string Index()
        {
            return "Hello from Home";
        }


按下F5运行应用程序,或者输入http://localhost:58716/Home/Index (Home就是控制器,Index是控制器类里的一个方法(Action))将返回如下:
 

 

三.添加StoreController控制器

     如法炮制,像上面一样添加StoreController控制器,然后添加几个方法代码如下:

   

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

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

    }
}


  运行程序分别输入http://localhost:58716/Store/Browse或者http://localhost:58716/Store/Details测试。

  那么在浏览器里如何向这个方法(Action)传参?

 我们继续添加一个方法:
 

  //
        // GET: /Store/GetMessage/5
        public string GetMessage(int id)
        {
            string message = "Store.Details, ID = " + id;
            return message;
        }


 运行程序输入http://localhost:58716/Store/GetMessage/5 或者http://localhost:58716/Store/GetMessage?id=10测试。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值