MVC中的控制器

authour: chenboyi
updatetime: 2015-04-25 12:22:35
friendly link:  

 

 

 


 

目录:

1,思维导图

2,控制器约定

3,action向视图传值的4中方式

4,ActionResult子类演示

5,获取参数的方式 (get/post)

6,在action中设置session和获取session

7,默认控制器工厂


 

1,思维导图:

MVC中的控制器_第1张图片

 

2,控制器约定

  1、控制器的后缀名一定是 Controller 结尾

  2、控制器必须继承Controller 父类
      3、方法控制器下的方法会去查询其Views文件夹下的和控制器同名目录下的和action同名的视图
      4、控制器中的action方法一定是public,否则会抛出404异常

  5、action方法可以返回基本的类型 和 void

  6、action方法返回一个类的对象的完全限定名

 

3,action向视图传值的4中方式:

  3.1.ViewData[]

  ViewData["list"] = list;

  CodeSimple:

  

 1 #region 1.0 通过ViewData向视图进行传值  2 public ActionResult Index()  3  {  4 //1.0 直接构造一个groupinf的list集合  5 List<GroupInfo> list = GetGlist();  6  7 //2.0 action向 视图传参  8 #region 2.0.1 通过ViewData["list"] 来传递  9
          ViewData["list"] = list;
10 #endregion 11 12 return View(); 13  } 14 #endregion

   3.2,ViewBag.x

  注意:ViewBag.x的本质是通过ViewData["x"]来传递的
  所以如果ViewBag.x 中的属性x 赋值之前已经通过viewdata["x"] 赋值了,则
  前一次的值会被后面的值覆盖

   CodeSimple:

  

 1 #region 3.0 通过ViewBag向视图进行传值  2  3 public ActionResult Index3()  4  {  5 string now = DateTime.Now.ToString();  6  7 //2.0 通过给ViewBag 动态添加一个now的属性进行传值  8 ViewBag.now = now;  9 10 return View(); 11  } 12 13 #endregion

   3.3 TempData[]

    CodeSimple:

1 public ActionResult Index2() 2  { 3 string str = "通过TempData传值"; 4 5 //2.0 通过TempData 进行传值 6  TempData["str"] = str; 7 8 return View(); 9 }

      3.4 View(object model)

    注意:View()通过Model传递给视图页面的 ,所以在.cshtml中是用Model来接收的

    CodeSimple:

 1  #region 4.0 通过View()方法向视图进行传值  2  3 public ActionResult Index4()  4  {  5 GroupInfo ginfo = new GroupInfo() { GroupID = 1, GroupName = "老板" };  6  7 //通过View()方法向视图进行传值  8 return View(ginfo);  9  } 10 11 #endregion

   3.5 向视图传递多个值

  CodeSimple:

 
1 public ActionResult Index5()
 2         {
 3             //注意:ViewData,TempData,ViewBag可以传递任何类型的值到视图
 4             //1.0 将名字传递到视图
 5             ViewData["name"] = "八戒";
 6 
 7             //2.0 将年龄传递给图
 8             //ViewData["age"] = "八戒";
 9             TempData["age"] = 500;
10 
11             //3.0 将性别传递到视图
12             ViewBag.Gender = "";
13 
14             //4.0 
15             ViewBag.name = "唐僧";16             ViewBag.age = 1000;
17 
18             return View();
19         }
 

  3.6 注意点

 ViewBag 本质上使用的是ViewData来传递的,所以ViewBag和ViewData存在相同key,那么后面那个的值会覆盖前面那个的值.
  view():本质上返回的是ViewResult,而ViewResult的父类是ViewResultBase,ViewResultBase 继承actionresult抽象类,所以能够在一个action中通过return view() 满足方法的返回值是ActionRsult的要求.
  action向视图传值的本质:是通过视图引擎将ViewResult对象实例传递给WebViewPage<Tmodel> 中的 Model 和 ViewData

 

4,ActionResult子类演示:

  ps:返回值类型推荐使用ActionResult做为返回值,而不是使用void和基本类型

  4.1 ViewResult(MVC开发中用的最多)

  ViewResult的父类是ViewResultBase,ViewResultBase 继承actionresult抽象类,所以能够在一个action中通过return view() 满足方法的返回值是ActionResult的要求.

  指定返回视图的几种方式:

    return View();

    return View("当前方法所在的控制器同名的文件夹下的视图名称");

    return View("/Views/Home/Index.cshtml");

    return View(obj);

    return View("当前方法所在的控制器同名的文件夹下的视图名称",obj)

  CodeSimple:

 1  public ActionResult TargetViewNameDemo()
 2         {
 3             //1.0 去views文件夹下查找和当前方法名称同名的视图
 4             // return View();
5 //2.0 去当前方法所在的控制器同名的文件夹下查找指定的 indexto.cshtml视图 6 // return View("indexto"); 7 8 //3.0 将 Views/Home/index.cshtml视图返回 9 // return View("/Views/Home/Index.cshtml"); 10 11 //4.0 将TargetViewName 文件夹下的indexto视图返回,同时向indexto.cshtml上传入一个对象 12 return View("indexto", new Dog() { uname = "小黑黑" }); 13 }

 

  4.2 ContentResult

    返回内容之用(特点,可以不需要有对应的视图)

    CodeSimple:

 1 #region 1.0 ActionResult 子类 ContentResult 演示
 2 
 3         public ActionResult ContentResultDemo()
 4         {
 5             return Content("服务器时间=" + DateTime.Now);
 6         }
 7 
 8         public ActionResult ContentResultjsDemo()
 9         {
10             return Content("<script>alert('我被执行啦!!!')</script>");
11         }
12 
13         public void ContentResultjsDemo1()
14         {
15             Response.Write("<script>alert('我被执行啦!!!')</script>");
16         }
17 
18         #endregion

 

  4.3 EmptyResult

  CodeSimple:

1 #region 2.0 EmptyResult () 演示
2 
3         public ActionResult EmptyResultDemo()
4         {
5             return new EmptyResult();
6         }
7 
8         #endregion

 

  4.4 FileResult

  可以用作画验证码,也可以利用它来实现文件的下载

  CodeSimple:

 1 #region 3.0 FileResult () 演示 (验证码制作)  2  3 public ActionResult FileResultDemo()  4  {  5 byte[] imgbuffer;  6 //1.0 实例化image对象  7 using (Image img = new Bitmap(65, 25))  8  {  9 //2.0 获取验证码 10 string vcode = "ab23"; 11 12 //3.0 将验证码存入session 13 Session["vcode"] = vcode; 14 15 //4.0 将验证码字符串画到图片上 16 using (Graphics g = Graphics.FromImage(img)) 17  { 18 //4.0.1 以白色背景填充位图 19  g.Clear(Color.White); 20 21 //4.0.2 画字符 22 g.DrawString(vcode, new Font("黑体", 16), new SolidBrush(Color.Red), 0, 0); 23  } 24 25 //5.0 将图片的流输出到imgbuffer中 26 using (MemoryStream ms = new MemoryStream()) 27  { 28 //5.0.1 将当前图片的流保存到ms中 29  img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 30 31 //5.0.2 将ms转换成byte【】数组 32 imgbuffer = ms.ToArray(); 33  } 34  } 35 return File(imgbuffer, "image/jpeg"); 36  } 37 #endregion

  4.5 JsonResult

  可以用作ajax请求 ,注意:如果是get请求,则一定是要在Json()中写入:JsonRequestBehavior.AllowGet

  CodeSimple:

 1 #region 4.0 JsonResult() 输出json格式字符串 演示
 2 
 3         public ActionResult JsonResultDemo()
 4         {
 5             //JsonResult会自动将对象序列化成json字符串,同时如果是get请求,则要将JsonRequestBehavior 设置成 AllowGet
 6             return Json(new { ID = 1, Name = "八戒" }, JsonRequestBehavior.AllowGet);  7 
 8             //如果浏览器(ajax的异步对象)发送的是post请求,写法如
 9             //return Json(new { ID = 1, Name = "八戒" });
10 
11         }

 

  4.6 HttpStatusCodeResult

  用户自己设置需要响应的状态码

  CodeSimple:

1   #region 5.0 HttpStatusCodeResult()自定义响应状态码
2 
3         public ActionResult HttpStatusCodeResultDemo()
4         {
5             //自定义响应状态码为404 :页面找不到 500 :服务器异常 304:缓存 302 :页面跳转  200:正常
6             return new HttpStatusCodeResult(404);
7         }
8 
9         #endregion

 

  4.6 JavaScriptResult

  注意:JavaScript配合视图中的<script rc="/GroupInfo/JavaScriptResultDemo1">

  CodeSimple:

 1 #region 6.0 JavaScriptResult 返回一段js脚本,一般配合ajax使用
 2 
 3         public ActionResult ViewResultDemo()
 4         {
 5             return View();
 6         }
 7 
 8         public ActionResult JavaScriptResultDemo()
 9         {
10             return JavaScript("alert('我被执行了')");
11         }
12 
13         #endregion
 1 html>
 2 <head>
 3     <meta name="viewport" content="width=device-width" />
 4     <title>ViewResultDemo</title>
 5     <script src="/C01ActionResultSubClass/JavaScriptResultDemo"></script>
 6 </head>
 7 <body>
 8     <div>
 9         我是调用JavaScriptResultDemo的视图
10     </div>
11 </body>
12 </html>

 

    4.7 RedirectResult

  执行页面跳转本质上是在响应报文头中产生了 Location:要跳转的页面的虚拟路径 命令

  CodeSimple:

#region 7.0 RedirectResult()页面跳转

        /// <summary>
        /// RedirectResult执行页面跳转的本质还是在响应报文头中添加了 Location指令集,并且将
        /// 响应状态码修改成302
        /// </summary>
        /// <returns></returns>
        public ActionResult RedirectResultDemo()
        {
            return Redirect("/ActionResultSubClass/FileResultDemo");
        }

    //等同于
public ActionResult RedirectResultDemo1() { Response.Redirect("/ActionResultSubClass/FileResultDemo"); return new EmptyResult(); } #endregion

 

    4.8 RedirectToRouteResult

  当系统中路由规则比较多的时候,可以由程序员指定使用哪个路由规则来生成url

  CodeSimple:

1  #region 8.0 RedirectToRouteResult()指定路由的页面跳转
2 
3         public ActionResult RedirectToRouteResultDemo()
4         {
5             //注意:参数可以直接使用匿名类来传递,匿名类中的属性名称一定要和路由规则中的url中的占位符名字保持一致
6             return RedirectToRoute(new { controller = "Home", action = "Index4", id = 100 });
7         }

 

    4.9 RedirectToAction

  CodeSimple:

 1   #region 9.0RedirectToAction 页面跳转
 2 
 3         public ActionResult RedirectToAction()
 4         {
 5             //跳转到同控制器的另外一个action
 6             //return RedirectToAction("JsonResultDemo");
 7 
 8             //跳转到home控制器的index4的action
 9             //return RedirectToAction("Index4", "Home");
10 
11             // 下面写法生成的结果url: http://localhost:14147/Home/Index/1000
12             // return RedirectToAction("Index", new { controller = "Home", id = 1000 });
13 
14             //下面写法生成的结果:http://localhost:14147/
15             return RedirectToAction("Index", new { controller = "Home" });
16 
17         }

 

 

5,获取参数的方式 (get/post)

   5.1 url传参(get请求)

  CodeSimple:

 1  #region 1.0 通过 QueryString【】 Params【】来接收url传入的参数
 2         //
 3         // GET: /getparms/   url:locahost/getparms/Index?id=1&name=2
 4         public ActionResult Index()
 5         {
 6             //1.0  通过QueryString
 7             //string id = Request.QueryString["id"];
 8             //string name = Request.QueryString["name"];
 9 
10             //2.0 通过Params
11             string id = Request.Params["id"];
12             string name = Request.Params["name"];
13 
14             ViewData["id"] = id;
15             ViewBag.name = name;
16 
17             return View();
18         } 
19         #endregion
20 
21         #region 2.0 通过 路由规则 + 方法参数 来接收url传入的参数
22         /// <summary>
23         /// url:  locahost/getparms/Index/1/2
24         /// 利用方法参数值 + 路由规则 来进行值的传递
25         /// MVC框架底层会智能的根据当前url匹配成功的路由规则来将参数解析出来以后
26         /// 赋值给当前方法的同名参数
27         /// </summary>
28         /// <param name="name"></param>
29         /// <param name="id"></param>
30         /// <returns></returns>
31         public ActionResult Index1(string name, string id)
32         {
33             //将浏览器传入的id参数 赋值给ViewBag.id 属性后,由视图引擎转交给视图类
34             ViewBag.id = id;
35             TempData["name"] = name;
36 
37             return View();
38         } 
39         #endregion

 

  5.2  请求报文体传参(post请求)

      post请求传参,主要有以下几种接受方式:

        通过request.Form["uname"]接收

        使用FormCollection

        通过在action方法中传入实体来接收参数 

      ps:

        在控制器中的一个方法上标记[HttpGet]和[HttpPost]区别:
           [HttpGet]:标记当前action方法只能被浏览器get请求
           [HttpPost]:标记当前action方法只能被浏览器Post请求
           如果一个方法上没有加[HttpGet]和[HttpPost],则表示此方法可以被浏览器get请求也可以post请求,不过默认是get请求     

  CodeSimple:

 1     #region 1.0 通过传统的 Form[]
 2         //
 3         // GET: /postparms/
 4         [HttpGet] //通过HttpGet 特性 标示当前index方法只处理get请求,但是HttpGet 是默认的,所以可以省略
 5         public ActionResult Index()
 6         {
 7             return View();
 8         }
 9 
10         [HttpPost] //通过HttpPost 特性 标示当前index方法只处理post请求
11         public ActionResult Index(string id)
12         {
13             //1.0 通过Form[]接收
14             string uname = Request.Form["uname"];
15             string uname1 = Request.Params["uname"];
16 
17             ViewBag.uname = uname;
18             ViewBag.uname1 = uname1;
19 
20             return View();
21         }
22         #endregion
23 
24         #region 2.0 通过在action方法中的FromCollection 对象来接收
25 
26         /// <summary>
27         /// 负责处理get请求
28         /// </summary>
29         /// <returns></returns>
30         public ActionResult index1()
31         {
32             return View();
33         }
34 
35         /// <summary>
36         /// 负责post请求
37         /// </summary>
38         /// <param name="id">和路由规则占位符{id}匹配</param>
39         /// <param name="forms">接收浏览器提交给服务器的表单集合,此处由于只有一个,可以使用forms[0]来处理</param>
40         /// <returns></returns>
41         [HttpPost]
42         public ActionResult index1(string id, FormCollection forms)
43         {
44             string uname = forms["uname"]; //uname=1&uname=2 -->  1,2
45 
46             //获取表单提交过来的参数
47             ViewBag.uname = uname;
48             //id:是获取url传入的参数
49             ViewBag.ID = id;
50 
51             return View();
52         }
53 
54         #endregion
55 
56         #region 3.0 通过在action方法中传入实体来接收参数
57 
58         [HttpGet]
59         public ActionResult Index3()
60         {
61             return View();
62         }
63 
64         /// <summary>
65         /// MVC底层会智能的将 请求报文体中的参数 uname=八戒,从pig对象中
66         /// 找到同名的属性 uname,将“八戒” 赋值给此属性
67         /// 注意:form表单中的 name属性的值 一定要在index3的Dog对象中有同名的属性,否则不会赋值
68         /// </summary>
69         /// <param name="id"></param>
70         /// <param name="pig"></param>
71         /// <returns></returns>
72         [HttpPost]
73         public ActionResult Index3(string id, Dog dog)
74         {
75             return View(dog);
76         }
77         #endregion

 

 6,在action中设置session和获取session:

  6.1 设置session

  CodeSimple:

 1   /// <summary>
 2         /// 负责设置session  ,发出get请求的时候设置session
 3         /// </summary>
 4         /// <returns></returns>
 5         [HttpGet]
 6         public ActionResult SetSession()
 7         {
 8             //1.0 设置session["uname"]
 9             Session["uname"] = "小蛮腰";
10             return View();
11         }

 

  6.2 获取session

  CodeSimple:

 1   /// <summary>
 2         /// post请求的时候 获取session
 3         /// </summary>
 4         /// <returns></returns>
 5         [HttpPost]
 6         public ActionResult GetSession()
 7         {
 8             string uname = Session["uname"].ToString();
 9             ViewBag.uname = uname;
10 
11             return View();
12         }

 

 

7,默认控制器工厂:

 

你可能感兴趣的:(mvc)