返璞归真 asp.net mvc (3) - Controller/Action
原文:返璞归真 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.cnblogs.com/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.cnblogs.com/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的更多相关文章
- 尝试asp.net mvc 基于controller action 方式权限控制方案可行性
微软在推出mvc框架不久,短短几年里,版本更新之快,真是大快人心,微软在这种优秀的框架上做了大量的精力投入,是值得赞同的,毕竟程序员驾驭在这种框架上,能够强力的精化代码,代码层次也更加优雅,扩展较为方 ...
- 尝试asp.net mvc 基于controller action 方式权限控制方案可行性(转载)
微软在推出mvc框架不久,短短几年里,版本更新之快,真是大快人心,微软在这种优秀的框架上做了大量的精力投入,是值得赞同的,毕竟程序员驾驭在这种框架上,能够强力的精化代码,代码层次也更加优雅,扩展较为方 ...
- 返璞归真 asp.net mvc (7) - asp.net mvc 3.0 新特性之 Controller
原文:返璞归真 asp.net mvc (7) - asp.net mvc 3.0 新特性之 Controller [索引页][源码下载] 返璞归真 asp.net mvc (7) - asp.net ...
- 返璞归真 asp.net mvc (5) - Action Filter, UpdateModel, ModelBinder, Ajax, Unit Test
原文:返璞归真 asp.net mvc (5) - Action Filter, UpdateModel, ModelBinder, Ajax, Unit Test [索引页] [源码下载] 返璞归真 ...
- 返璞归真 asp.net mvc (13) - asp.net mvc 5.0 新特性
[索引页][源码下载] 返璞归真 asp.net mvc (13) - asp.net mvc 5.0 新特性 作者:webabcd 介绍asp.net mvc 之 asp.net mvc 5.0 新 ...
- 返璞归真 asp.net mvc (8) - asp.net mvc 3.0 新特性之 Model
原文:返璞归真 asp.net mvc (8) - asp.net mvc 3.0 新特性之 Model [索引页][源码下载] 返璞归真 asp.net mvc (8) - asp.net mvc ...
- 返璞归真 asp.net mvc (4) - View/ViewEngine
原文:返璞归真 asp.net mvc (4) - View/ViewEngine [索引页] [源码下载] 返璞归真 asp.net mvc (4) - View/ViewEngine 作者:web ...
- 返璞归真 asp.net mvc (2) - 路由(System.Web.Routing)
原文:返璞归真 asp.net mvc (2) - 路由(System.Web.Routing) [索引页] [源码下载] 返璞归真 asp.net mvc (2) - 路由(System.Web.R ...
- 返璞归真 asp.net mvc (1) - 添加、查询、更新和删除的 Demo
原文:返璞归真 asp.net mvc (1) - 添加.查询.更新和删除的 Demo [索引页] [源码下载] 返璞归真 asp.net mvc (1) - 添加.查询.更新和删除的 Demo 作者 ...
随机推荐
- 分布式发布订阅消息系统Kafka
高吞吐量的分布式发布订阅消息系统Kafka--安装及测试 一.Kafka概述 Kafka是一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者规模的网站中的所有动作流数据. 这种动作(网页浏览, ...
- 胡na娜、少年和恩师-写在甲午冬的仅仅言片语及感想
[写在全新为移动互联网而生的Zoomla!逐浪CMS2 x2.1公布前] 恩师, 他来到这个乡村中学,带着自己的书.吉它和理想, 用自己最好的三年青春浇灌了这一代人, 在我辍学时,给我鼓舞,帮助我继续 ...
- [置顶] 一步一步学android之事件篇——下拉列表事件
上一篇RadioGroup比较简单,所以再学习个spinner的OnItemSelectedListener事件,前面说过spinner的主要功能就是提供列表显示的选择,比如我们在选择城市的时候就会用 ...
- SSDTHook实例--编写稳定的Hook过滤函数
解说怎样写Hook过滤函数,比方NewZwOpenProcess.打开进程. 非常多游戏保护都会对这个函数进行Hook. 因为我们没有游戏保护的代码,无法得知游戏公司是怎样编写这个过滤函数. 我看到非 ...
- Android中振动器(Vibrator)的使用
系统获取Vibrator也是调用Context的getSystemService方法,接下来就可以调用Vibrator的方法控制手机振动了.Vibrator只有三个方法控制手机振动: 1.vibrat ...
- error U1087: cannot have : and :: dependents for same target
windows驱动开发遇到错误: 1>e:\winddk\7600\bin\makefile.new(7117) : error U1087: cannot have : and :: depe ...
- 《JavaScript设计模式与开发实践》读书笔记之代理模式
1.代理模式 代理模式是为一个对象提供一个代用品或占位符,以便控制对它的访问 1.1 一般的图片加载 var myImage=(function () { var imgNode=document.c ...
- html 跳转页面,同时跳转到一个指定的位置
比如我现在 a.html 的时候,我想跳转到 b.html ,并且是 b.html 的某一个位置,用 <a href=>, a.html里: <a href="b.html ...
- 从lca到树链剖分 bestcoder round#45 1003
bestcoder round#45 1003 题,给定两个点,要我们求这两个点的树上路径所经过的点的权值是否出现过奇数次.如果是一般人,那么就是用lca求树上路径,然后判断是否出现过奇数次(用异或) ...
- 为VS2013添加SQLCE的支持
解决 下载SQL Server Compact Toolbox by ErikEJ并安装 打开VS2013,新建一工程,在“视图>其它窗口>SQL Server Compact Toolb ...