返璞歸真 asp.net mvc (3) - Controller/Action
[索引頁]
[源碼下載]
作者:webabcd
介紹
asp.net mvc 之 Controller 和 Action
示例
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
{
/// <summary>
/// Controller 類必須以字符串 "Controller" 做類名稱的結尾,字符串 Controller 之前的字符串為 Controller 的名稱,類中的方法名為 Action 的名稱
/// </summary>
public class ControllerDemoController : Controller
{
// [NonAction] - 當前方法僅為普通方法,不解析為 Action
// [AcceptVerbs(HttpVerbs.Post)] - 聲明 Action 所對應的 http 方法

/// <summary>
/// Action 可以沒有返回值
/// </summary>
public void Void()
{
Response.Write(string.Format("<span style='color: red'>{0}</span>", "void"));
}

/// <summary>
/// 如果 Action 要有返回值的話,其類型必須是 ActionResult
/// EmptyResult - 空結果
/// </summary>
public ActionResult EmptyResult()
{
Response.Write(string.Format("<span style='color: red'>{0}</span>", "EmptyResult"));
return new EmptyResult();
}

/// <summary>
/// Controller.Redirect() - 轉向一個指定的 url 地址
/// 返回類型為 RedirectResult
/// </summary>
public ActionResult RedirectResult()
{
return base.Redirect("~/ControllerDemo/ContentResult");
}

/// <summary>
/// Controller.RedirectToAction() - 轉向到指定的 Action
/// 返回類型為 RedirectToRouteResult
/// </summary>
public ActionResult RedirectToRouteResult()
{
return base.RedirectToAction("ContentResult");
}

/// <summary>
/// Controller.Json() - 將指定的對象以 JSON 格式輸出出來
/// 返回類型為 JsonResult
/// </summary>
public ActionResult JsonResult(string name)
{
System.Threading.Thread.Sleep(1000);

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

/// <summary>
/// Controller.JavaScript() - 輸出一段指定的 JavaScript 腳本
/// 返回類型為 JavaScriptResult
/// </summary>
public ActionResult JavaScriptResult()
{
return base.JavaScript("alert('JavaScriptResult')");
}

/// <summary>
/// Controller.Content() - 輸出一段指定的內容
/// 返回類型為 ContentResult
/// </summary>
public ActionResult ContentResult()
{
string contentString = string.Format("<span style='color: red'>{0}</span>", "ContentResult");
return base.Content(contentString);
}

/// <summary>
/// Controller.File() - 輸出一個文件(字節數組)
/// 返回類型為 FileContentResult
/// </summary>
public 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");
}

// <summary>
/// Controller.File() - 輸出一個文件(文件地址)
/// 返回類型為 FileContentResult
/// </summary>
public ActionResult FilePathResult()
{
var path = Request.PhysicalApplicationPath + "Content/loading.gif";
return base.File(path, "image/gif");
}

// <summary>
/// Controller.File() - 輸出一個文件(文件流)
/// 返回類型為 FileContentResult
/// </summary>
public ActionResult FileStreamResult()
{
FileStream fs = new FileStream(Request.PhysicalApplicationPath + "Content/loading.gif", FileMode.Open);

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

/// <summary>
/// HttpUnauthorizedResult - 響應給客戶端錯誤代碼 401(未經授權瀏覽狀態),如果程序啟用了 Forms 驗證,并且客戶端沒有任何身份票據,則會跳轉到指定的登錄頁
/// </summary>
public ActionResult HttpUnauthorizedResult()
{
return new HttpUnauthorizedResult();
}

/// <summary>
/// Controller.PartialView() - 尋找 View ,即 .ascx 文件
/// 返回類型為 PartialViewResult
/// </summary>
public ActionResult PartialViewResult()
{
return base.PartialView();
}

/// <summary>
/// Controller.View() - 尋找 View ,即 .aspx 文件
/// 返回類型為 ViewResult
/// </summary>
public ActionResult ViewResult()
{
// 如果沒有指定 View 名稱,則尋找與 Action 名稱相同的 View
return base.View();
}

/// <summary>
/// 用于演示處理 JSON 的
/// </summary>
public ActionResult JsonDemo()
{
return View();
}

/// <summary>
/// 用于演示上傳文件的
/// </summary>
public ActionResult UploadDemo()
{
return View();
}

/// <summary>
/// 用于演示 Get 方式調用 Action
/// id 是根據路由過來的;param1和param2是根據參數過來的
/// </summary>
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetDemo(int id, string param1, string param2)
{
ViewData["ID"] = id;
ViewData["Param1"] = param1;
ViewData["Param2"] = param2;

return View();
}

/// <summary>
/// 用于演示 Post 方式調用 Action
/// </summary>
/// <remarks>
/// 可以為參數添加聲明,如:[Bind(Include = "xxx")] - 只綁定指定的屬性(參數),多個用逗號隔開
/// [Bind(Exclude = "xxx")] - 不綁定指定的屬性(參數),多個用逗號隔開
/// [Bind] 聲明同樣可以作用于 class 上
/// </remarks>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult PostDemo(FormCollection fc)
{
ViewData["Param1"] = fc["param1"];
ViewData["Param2"] = fc["param2"];

// 也可以用 Request.Form 方式獲取 post 過來的參數

// Request.Form 內的參數也會映射到同名參數。例如,也可用如下方式獲取參數
// public ActionResult PostDemo(string param1, string param2)

return View("GetDemo");
}

/// <summary>
/// 處理上傳文件的 Action
/// </summary>
/// <param name="file1">與傳過來的 file 類型的 input 的 name 相對應</param>
[AcceptVerbs(HttpVerbs.Post)]
public 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
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
GetDemo
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
GetDemo</h2>
<div>
<%= ViewData["ID"] %></div>
<div>
<%= ViewData["Param1"] %></div>
<div>
<%= ViewData["Param2"] %></div>
<form action="/ControllerDemo/PostDemo" method="post">
<input id="param1" name="param1" />
<input id="param2" name="param2" />
<input type="submit" value="submit" />
</form>
</asp:Content>
3、處理 JSON 的 Demo
JsonDemo.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
JsonDemo
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<script src="http://www.rzrgm.cn/Scripts/jquery-1.3.2.js" type="text/javascript"></script>

<script type="text/javascript">

$.ajaxSetup({
cache: false
});

$(document).ready(
function() {

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

$('#btnFind').click(
function(event) {
event.preventDefault();

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

$.getJSON(
"/ControllerDemo/JsonResult", // 獲取 JSON
{ name: $('#txtName')[0].value },
function(data) {
$('#result').append("name: ");
$('#result').append(data.Name);
$('#result').append(" - ");
$('#result').append("age: ");
$('#result').append(data.Age);
$('#result').append("<br />");

$('#loading').hide();
}
)
}
)
}
)
</script>

<h2>
JsonDemo</h2>
<div style="margin: 20px 0px">
<input id="txtName" value="webabcd" />
<a href="#" id="btnFind">Find</a> <span id="loading" style="border: 1px solid #000000;
background-color: #FFFFCC; vertical-align: middle; padding: 6px">
<img src="http://www.rzrgm.cn/Content/Images/loading.gif" alt="Loading" /> Loading
</span>
<div id="result" style="margin: 10px 0px" />
</div>
</asp:Content>
4、上傳文件的 Demo
UploadDemo.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
UploadDemo
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
UploadDemo</h2>
<!--action - 調用上傳文件的 Action-->
<form action="/ControllerDemo/UploadFile" method="post" enctype="multipart/form-data">
<input type="file" id="file1" name="file1" />
<input type="submit" id="upload" name="upload" value="上傳" />
</form>
</asp:Content>
OK
[源碼下載]
[源碼下載]
返璞歸真 asp.net mvc (3) - Controller/Action
作者:webabcd
介紹
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
{
/// <summary>
/// Controller 類必須以字符串 "Controller" 做類名稱的結尾,字符串 Controller 之前的字符串為 Controller 的名稱,類中的方法名為 Action 的名稱
/// </summary>
public class ControllerDemoController : Controller
{
// [NonAction] - 當前方法僅為普通方法,不解析為 Action
// [AcceptVerbs(HttpVerbs.Post)] - 聲明 Action 所對應的 http 方法
/// <summary>
/// Action 可以沒有返回值
/// </summary>
public void Void()
{
Response.Write(string.Format("<span style='color: red'>{0}</span>", "void"));
}
/// <summary>
/// 如果 Action 要有返回值的話,其類型必須是 ActionResult
/// EmptyResult - 空結果
/// </summary>
public ActionResult EmptyResult()
{
Response.Write(string.Format("<span style='color: red'>{0}</span>", "EmptyResult"));
return new EmptyResult();
}
/// <summary>
/// Controller.Redirect() - 轉向一個指定的 url 地址
/// 返回類型為 RedirectResult
/// </summary>
public ActionResult RedirectResult()
{
return base.Redirect("~/ControllerDemo/ContentResult");
}
/// <summary>
/// Controller.RedirectToAction() - 轉向到指定的 Action
/// 返回類型為 RedirectToRouteResult
/// </summary>
public ActionResult RedirectToRouteResult()
{
return base.RedirectToAction("ContentResult");
}
/// <summary>
/// Controller.Json() - 將指定的對象以 JSON 格式輸出出來
/// 返回類型為 JsonResult
/// </summary>
public ActionResult JsonResult(string name)
{
System.Threading.Thread.Sleep(1000);
var jsonObj = new { Name = name, Age = new Random().Next(20, 31) };
return base.Json(jsonObj);
}
/// <summary>
/// Controller.JavaScript() - 輸出一段指定的 JavaScript 腳本
/// 返回類型為 JavaScriptResult
/// </summary>
public ActionResult JavaScriptResult()
{
return base.JavaScript("alert('JavaScriptResult')");
}
/// <summary>
/// Controller.Content() - 輸出一段指定的內容
/// 返回類型為 ContentResult
/// </summary>
public ActionResult ContentResult()
{
string contentString = string.Format("<span style='color: red'>{0}</span>", "ContentResult");
return base.Content(contentString);
}
/// <summary>
/// Controller.File() - 輸出一個文件(字節數組)
/// 返回類型為 FileContentResult
/// </summary>
public 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");
}
// <summary>
/// Controller.File() - 輸出一個文件(文件地址)
/// 返回類型為 FileContentResult
/// </summary>
public ActionResult FilePathResult()
{
var path = Request.PhysicalApplicationPath + "Content/loading.gif";
return base.File(path, "image/gif");
}
// <summary>
/// Controller.File() - 輸出一個文件(文件流)
/// 返回類型為 FileContentResult
/// </summary>
public ActionResult FileStreamResult()
{
FileStream fs = new FileStream(Request.PhysicalApplicationPath + "Content/loading.gif", FileMode.Open);
return base.File(fs, @"image/gif");
}
/// <summary>
/// HttpUnauthorizedResult - 響應給客戶端錯誤代碼 401(未經授權瀏覽狀態),如果程序啟用了 Forms 驗證,并且客戶端沒有任何身份票據,則會跳轉到指定的登錄頁
/// </summary>
public ActionResult HttpUnauthorizedResult()
{
return new HttpUnauthorizedResult();
}
/// <summary>
/// Controller.PartialView() - 尋找 View ,即 .ascx 文件
/// 返回類型為 PartialViewResult
/// </summary>
public ActionResult PartialViewResult()
{
return base.PartialView();
}
/// <summary>
/// Controller.View() - 尋找 View ,即 .aspx 文件
/// 返回類型為 ViewResult
/// </summary>
public ActionResult ViewResult()
{
// 如果沒有指定 View 名稱,則尋找與 Action 名稱相同的 View
return base.View();
}
/// <summary>
/// 用于演示處理 JSON 的
/// </summary>
public ActionResult JsonDemo()
{
return View();
}
/// <summary>
/// 用于演示上傳文件的
/// </summary>
public ActionResult UploadDemo()
{
return View();
}
/// <summary>
/// 用于演示 Get 方式調用 Action
/// id 是根據路由過來的;param1和param2是根據參數過來的
/// </summary>
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetDemo(int id, string param1, string param2)
{
ViewData["ID"] = id;
ViewData["Param1"] = param1;
ViewData["Param2"] = param2;
return View();
}
/// <summary>
/// 用于演示 Post 方式調用 Action
/// </summary>
/// <remarks>
/// 可以為參數添加聲明,如:[Bind(Include = "xxx")] - 只綁定指定的屬性(參數),多個用逗號隔開
/// [Bind(Exclude = "xxx")] - 不綁定指定的屬性(參數),多個用逗號隔開
/// [Bind] 聲明同樣可以作用于 class 上
/// </remarks>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult PostDemo(FormCollection fc)
{
ViewData["Param1"] = fc["param1"];
ViewData["Param2"] = fc["param2"];
// 也可以用 Request.Form 方式獲取 post 過來的參數
// Request.Form 內的參數也會映射到同名參數。例如,也可用如下方式獲取參數
// public ActionResult PostDemo(string param1, string param2)
return View("GetDemo");
}
/// <summary>
/// 處理上傳文件的 Action
/// </summary>
/// <param name="file1">與傳過來的 file 類型的 input 的 name 相對應</param>
[AcceptVerbs(HttpVerbs.Post)]
public 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
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
GetDemo
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
GetDemo</h2>
<div>
<%= ViewData["ID"] %></div>
<div>
<%= ViewData["Param1"] %></div>
<div>
<%= ViewData["Param2"] %></div>
<form action="/ControllerDemo/PostDemo" method="post">
<input id="param1" name="param1" />
<input id="param2" name="param2" />
<input type="submit" value="submit" />
</form>
</asp:Content>
3、處理 JSON 的 Demo
JsonDemo.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
JsonDemo
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="http://www.rzrgm.cn/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$.ajaxSetup({
cache: false
});
$(document).ready(
function() {
$('#loading').hide();
$('#btnFind').click(
function(event) {
event.preventDefault();
$('#loading').show();
$.getJSON(
"/ControllerDemo/JsonResult", // 獲取 JSON
{ name: $('#txtName')[0].value },
function(data) {
$('#result').append("name: ");
$('#result').append(data.Name);
$('#result').append(" - ");
$('#result').append("age: ");
$('#result').append(data.Age);
$('#result').append("<br />");
$('#loading').hide();
}
)
}
)
}
)
</script>
<h2>
JsonDemo</h2>
<div style="margin: 20px 0px">
<input id="txtName" value="webabcd" />
<a href="#" id="btnFind">Find</a> <span id="loading" style="border: 1px solid #000000;
background-color: #FFFFCC; vertical-align: middle; padding: 6px">
<img src="http://www.rzrgm.cn/Content/Images/loading.gif" alt="Loading" /> Loading
</span>
<div id="result" style="margin: 10px 0px" />
</div>
</asp:Content>
4、上傳文件的 Demo
UploadDemo.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
UploadDemo
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
UploadDemo</h2>
<!--action - 調用上傳文件的 Action-->
<form action="/ControllerDemo/UploadFile" method="post" enctype="multipart/form-data">
<input type="file" id="file1" name="file1" />
<input type="submit" id="upload" name="upload" value="上傳" />
</form>
</asp:Content>
OK
[源碼下載]

浙公網安備 33010602011771號