天天看点

返璞归真 asp.net mvc (3) - Controller/Action

<a href="http://webabcd.blog.51cto.com/1787395/341060" target="_blank">[索引页]</a>

<a href="http://down.51cto.com/data/99931" target="_blank">[源码下载]</a>

返璞归真 asp.net mvc (3) - Controller/Action

介绍

asp.net mvc 之 Controller 和 Action

Controller 类必须以字符串 "Controller" 做类名称的结尾,字符串 Controller 之前的字符串为 Controller 的名称,类中的方法名为 Action 的名称

Action 可以没有返回值。如果 Action 要有返回值的话,其类型必须是 ActionResult

示例

1、Controller/Action

ControllerDemoController.cs

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Web; 

using System.Web.Mvc; 

using System.Web.Mvc.Ajax; 

using System.IO; 

namespace MVC.Controllers 

        /**//// &lt;summary&gt; 

        /// Controller 类必须以字符串 "Controller" 做类名称的结尾,字符串 Controller 之前的字符串为 Controller 的名称,类中的方法名为 Action 的名称 

        /// &lt;/summary&gt; 

        public class ControllerDemoController : Controller 

        { 

                // [NonAction] - 当前方法仅为普通方法,不解析为 Action 

                // [AcceptVerbs(HttpVerbs.Post)] - 声明 Action 所对应的 http 方法 

                /**//// &lt;summary&gt; 

                /// Action 可以没有返回值 

                /// &lt;/summary&gt; 

void Void() void Void() 

                { 

                        Response.Write(string.Format("&lt;span style='color: red'&gt;{0}&lt;/span&gt;", "void")); 

                } 

                /// 如果 Action 要有返回值的话,其类型必须是 ActionResult 

                /// EmptyResult - 空结果 

ActionResult EmptyResult() ActionResult EmptyResult() 

                        Response.Write(string.Format("&lt;span style='color: red'&gt;{0}&lt;/span&gt;", "EmptyResult")); 

                        return new EmptyResult(); 

                /// Controller.Redirect() - 转向一个指定的 url 地址 

                /// 返回类型为 RedirectResult 

ActionResult RedirectResult() ActionResult RedirectResult() 

                        return base.Redirect("~/ControllerDemo/ContentResult"); 

                /// Controller.RedirectToAction() - 转向到指定的 Action 

                /// 返回类型为 RedirectToRouteResult 

ActionResult RedirectToRouteResult() ActionResult RedirectToRouteResult() 

                        return base.RedirectToAction("ContentResult"); 

                /// Controller.Json() - 将指定的对象以 JSON 格式输出出来 

                /// 返回类型为 JsonResult 

ActionResult JsonResult() ActionResult JsonResult(string name) 

                        System.Threading.Thread.Sleep(1000); 

                        var jsonObj = new { Name = name, Age = new Random().Next(20, 31) }; 

                        return base.Json(jsonObj); 

                /// Controller.JavaScript() - 输出一段指定的 JavaScript 脚本 

                /// 返回类型为 JavaScriptResult 

ActionResult JavaScriptResult() ActionResult JavaScriptResult() 

                        return base.JavaScript("alert('JavaScriptResult')"); 

                /// Controller.Content() - 输出一段指定的内容 

                /// 返回类型为 ContentResult 

ActionResult ContentResult() ActionResult ContentResult() 

                        string contentString = string.Format("&lt;span style='color: red'&gt;{0}&lt;/span&gt;", "ContentResult"); 

                        return base.Content(contentString); 

                /// Controller.File() - 输出一个文件(字节数组) 

                /// 返回类型为 FileContentResult 

ActionResult FileContentResult() ActionResult FileContentResult() 

                        FileStream fs = new FileStream(Request.PhysicalApplicationPath + "Content/loading.gif", FileMode.Open); 

                        int length = (int)fs.Length; 

                        byte[] buffer = new byte[length]; 

                        fs.Read(buffer, 0, length); 

                        fs.Close(); 

                        return base.File(buffer, "image/gif"); 

                // &lt;summary&gt; 

                /**//// Controller.File() - 输出一个文件(文件地址) 

ActionResult FilePathResult() ActionResult FilePathResult() 

                        var path = Request.PhysicalApplicationPath + "Content/loading.gif"; 

                        return base.File(path, "image/gif"); 

                /**//// Controller.File() - 输出一个文件(文件流) 

ActionResult FileStreamResult() ActionResult FileStreamResult() 

                        return base.File(fs, @"image/gif"); 

                /// HttpUnauthorizedResult - 响应给客户端错误代码 401(未经授权浏览状态),如果程序启用了 Forms 验证,并且客户端没有任何身份票据,则会跳转到指定的登录页 

ActionResult HttpUnauthorizedResult() ActionResult HttpUnauthorizedResult() 

                        return new HttpUnauthorizedResult(); 

                /// Controller.PartialView() - 寻找 View ,即 .ascx 文件 

                /// 返回类型为 PartialViewResult 

ActionResult PartialViewResult() ActionResult PartialViewResult() 

                        return base.PartialView(); 

                /// Controller.View() - 寻找 View ,即 .aspx 文件 

                /// 返回类型为 ViewResult 

ActionResult ViewResult() ActionResult ViewResult() 

                        // 如果没有指定 View 名称,则寻找与 Action 名称相同的 View 

                        return base.View(); 

                /// 用于演示处理 JSON 的 

ActionResult JsonDemo() ActionResult JsonDemo() 

                        return View(); 

                /// 用于演示上传文件的 

ActionResult UploadDemo() ActionResult UploadDemo() 

                /// 用于演示 Get 方式调用 Action 

                /// id 是根据路由过来的;param1和param2是根据参数过来的 

                [AcceptVerbs(HttpVerbs.Get)] 

ActionResult GetDemo() ActionResult GetDemo(int id, string param1, string param2) 

                        ViewData["ID"] = id; 

                        ViewData["Param1"] = param1; 

                        ViewData["Param2"] = param2; 

                /// 用于演示 Post 方式调用 Action 

                /// &lt;remarks&gt; 

                /// 可以为参数添加声明,如:[Bind(Include = "xxx")] - 只绑定指定的属性(参数),多个用逗号隔开 

                /// [Bind(Exclude = "xxx")] - 不绑定指定的属性(参数),多个用逗号隔开 

                /// [Bind] 声明同样可以作用于 class 上 

                /// &lt;/remarks&gt; 

                [AcceptVerbs(HttpVerbs.Post)] 

ActionResult PostDemo() ActionResult PostDemo(FormCollection fc) 

                        ViewData["Param1"] = fc["param1"]; 

                        ViewData["Param2"] = fc["param2"]; 

                        // 也可以用 Request.Form 方式获取 post 过来的参数 

                        // Request.Form 内的参数也会映射到同名参数。例如,也可用如下方式获取参数     

ActionResult PostDemo() ActionResult PostDemo(string param1, string param2) 

                        return View("GetDemo"); 

                /// 处理上传文件的 Action 

                /// &lt;param name="file1"&gt;与传过来的 file 类型的 input 的 name 相对应&lt;/param&gt; 

ActionResult UploadFile() ActionResult UploadFile(HttpPostedFileBase file1) 

                        // Request.Files - 获取需要上传的文件。当然,其也会自动映射到同名参数 

                        // HttpPostedFileBase hpfb = Request.Files[0] as HttpPostedFileBase; 

                        string targetPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Upload", Path.GetFileName(file1.FileName)); 

                        file1.SaveAs(targetPath); 

                        return View("UploadDemo"); 

        } 

}

2、Get 方式和 Post 方式调用 Controller 的 Demo

GetDemo.aspx

&lt;%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %&gt; 

&lt;asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"&gt; 

        GetDemo 

&lt;/asp:Content&gt; 

&lt;asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"&gt; 

        &lt;h2&gt; 

                GetDemo&lt;/h2&gt; 

        &lt;div&gt; 

                &lt;%= ViewData["ID"] %&gt;&lt;/div&gt; 

                &lt;%= ViewData["Param1"] %&gt;&lt;/div&gt; 

                &lt;%= ViewData["Param2"] %&gt;&lt;/div&gt; 

        &lt;form action="/ControllerDemo/PostDemo" method="post"&gt; 

        &lt;input id="param1" name="param1" /&gt; 

        &lt;input id="param2" name="param2" /&gt; 

        &lt;input type="submit" value="submit" /&gt; 

        &lt;/form&gt; 

&lt;/asp:Content&gt;

3、处理 JSON 的 Demo

JsonDemo.aspx

        JsonDemo 

        &lt;script src="http://www.cnblogs.com/Scripts/jquery-1.3.2.js" type="text/javascript"&gt;&lt;/script&gt; 

        &lt;script type="text/javascript"&gt; 

                $.ajaxSetup({ 

                        cache: false 

                }); 

                $(document).ready( 

()() { 

                                $('#loading').hide(); 

                                $('#btnFind').click( 

()(event) { 

                                                event.preventDefault(); 

                                                $('#loading').show(); 

                                                $.getJSON( 

                                                        "/ControllerDemo/JsonResult", // 获取 JSON 

                                                        { name: $('#txtName')[0].value }, 

()(data) { 

                                                                $('#result').append("name: "); 

                                                                $('#result').append(data.Name); 

                                                                $('#result').append(" - "); 

                                                                $('#result').append("age: "); 

                                                                $('#result').append(data.Age); 

                                                                $('#result').append("&lt;br /&gt;"); 

                                                                $('#loading').hide(); 

                                                        } 

                                                ) 

                                        } 

                                ) 

                        } 

                ) 

        &lt;/script&gt; 

                JsonDemo&lt;/h2&gt; 

        &lt;div style="margin: 20px 0px"&gt; 

                &lt;input id="txtName" value="webabcd" /&gt; 

                   &lt;a href="#" id="btnFind"&gt;Find&lt;/a&gt;    &lt;span id="loading" style="border: 1px solid #000000; 

                        background-color: #FFFFCC; vertical-align: middle; padding: 6px"&gt; 

                        &lt;img src="http://www.cnblogs.com/Content/Images/loading.gif" alt="Loading" /&gt; Loading&lt;/span&gt; 

                &lt;div id="result" style="margin: 10px 0px" /&gt; 

        &lt;/div&gt; 

4、上传文件的 Demo

UploadDemo.aspx

        UploadDemo 

                UploadDemo&lt;/h2&gt; 

        &lt;!--action - 调用上传文件的 Action--&gt; 

        &lt;form action="/ControllerDemo/UploadFile" method="post" enctype="multipart/form-data"&gt; 

        &lt;input type="file" id="file1" name="file1" /&gt; 

        &lt;input type="submit" id="upload" name="upload" value="上传" /&gt; 

OK

     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/341602,如需转载请自行联系原作者

继续阅读