天天看點

返璞歸真 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,如需轉載請自行聯系原作者

繼續閱讀