博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
返璞归真 asp.net mvc (3) - Controller/Action
阅读量:7217 次
发布时间:2019-06-29

本文共 8200 字,大约阅读时间需要 27 分钟。

原文:

返璞归真 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
ExpandedBlockStart.gifContractedBlock.gif
{
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
    
/// Controller 类必须以字符串 "Controller" 做类名称的结尾,字符串 Controller 之前的字符串为 Controller 的名称,类中的方法名为 Action 的名称
    
/// </summary>
    public class ControllerDemoController : Controller
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
// [NonAction] - 当前方法仅为普通方法,不解析为 Action
        
// [AcceptVerbs(HttpVerbs.Post)] - 声明 Action 所对应的 http 方法
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Action 可以没有返回值
        
/// </summary>
        public void Void()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Response.Write(
string.Format("<span style='color: red'>{0}</span>""void"));
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 如果 Action 要有返回值的话,其类型必须是 ActionResult
        
/// EmptyResult - 空结果
        
/// </summary>
        public ActionResult EmptyResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            Response.Write(
string.Format("<span style='color: red'>{0}</span>""EmptyResult"));
            
return new EmptyResult();
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Controller.Redirect() - 转向一个指定的 url 地址
        
/// 返回类型为 RedirectResult
        
/// </summary>
        public ActionResult RedirectResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return base.Redirect("~/ControllerDemo/ContentResult");
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Controller.RedirectToAction() - 转向到指定的 Action
        
/// 返回类型为 RedirectToRouteResult
        
/// </summary>
        public ActionResult RedirectToRouteResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return base.RedirectToAction("ContentResult");
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Controller.Json() - 将指定的对象以 JSON 格式输出出来
        
/// 返回类型为 JsonResult
        
/// </summary>
        public ActionResult JsonResult(string name)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            System.Threading.Thread.Sleep(
1000);
ExpandedSubBlockStart.gifContractedSubBlock.gif            var jsonObj 
= new { Name = name, Age = new Random().Next(2031) };
            
return base.Json(jsonObj);
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Controller.JavaScript() - 输出一段指定的 JavaScript 脚本
        
/// 返回类型为 JavaScriptResult
        
/// </summary>
        public ActionResult JavaScriptResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return base.JavaScript("alert('JavaScriptResult')");
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Controller.Content() - 输出一段指定的内容
        
/// 返回类型为 ContentResult
        
/// </summary>
        public ActionResult ContentResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
string contentString = string.Format("<span style='color: red'>{0}</span>""ContentResult");
            
return base.Content(contentString);
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Controller.File() - 输出一个文件(字节数组)
        
/// 返回类型为 FileContentResult
        
/// </summary>
        public ActionResult FileContentResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            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>
ExpandedSubBlockStart.gifContractedSubBlock.gif
        /**//// Controller.File() - 输出一个文件(文件地址)
        
/// 返回类型为 FileContentResult
        
/// </summary>
        public ActionResult FilePathResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            var path 
= Request.PhysicalApplicationPath + "Content/loading.gif";
            
return base.File(path, "image/gif");
        }
        
// <summary>
ExpandedSubBlockStart.gifContractedSubBlock.gif
        /**//// Controller.File() - 输出一个文件(文件流)
        
/// 返回类型为 FileContentResult
        
/// </summary>
        public ActionResult FileStreamResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            FileStream fs 
= new FileStream(Request.PhysicalApplicationPath + "Content/loading.gif", FileMode.Open);
            
return base.File(fs, @"image/gif");
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// HttpUnauthorizedResult - 响应给客户端错误代码 401(未经授权浏览状态),如果程序启用了 Forms 验证,并且客户端没有任何身份票据,则会跳转到指定的登录页
        
/// </summary>
        public ActionResult HttpUnauthorizedResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return new HttpUnauthorizedResult();
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Controller.PartialView() - 寻找 View ,即 .ascx 文件
        
/// 返回类型为 PartialViewResult
        
/// </summary>
        public ActionResult PartialViewResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return base.PartialView();
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// Controller.View() - 寻找 View ,即 .aspx 文件
        
/// 返回类型为 ViewResult
        
/// </summary>
        public ActionResult ViewResult()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
// 如果没有指定 View 名称,则寻找与 Action 名称相同的 View
            return base.View();
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 用于演示处理 JSON 的
        
/// </summary>
        public ActionResult JsonDemo()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return View();
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 用于演示上传文件的
        
/// </summary>
        public ActionResult UploadDemo()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
return View();
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 用于演示 Get 方式调用 Action
        
/// id 是根据路由过来的;param1和param2是根据参数过来的
        
/// </summary>
        [AcceptVerbs(HttpVerbs.Get)]
        
public ActionResult GetDemo(int id, string param1, string param2)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            ViewData[
"ID"= id;
            ViewData[
"Param1"= param1;
            ViewData[
"Param2"= param2;
            
return View();
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 用于演示 Post 方式调用 Action
        
/// </summary>
        
/// <remarks>
        
/// 可以为参数添加声明,如:[Bind(Include = "xxx")] - 只绑定指定的属性(参数),多个用逗号隔开
        
/// [Bind(Exclude = "xxx")] - 不绑定指定的属性(参数),多个用逗号隔开
        
/// [Bind] 声明同样可以作用于 class 上
        
/// </remarks>
        [AcceptVerbs(HttpVerbs.Post)]
        
public ActionResult PostDemo(FormCollection fc)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            ViewData[
"Param1"= fc["param1"];
            ViewData[
"Param2"= fc["param2"];
            
// 也可以用 Request.Form 方式获取 post 过来的参数
            
// Request.Form 内的参数也会映射到同名参数。例如,也可用如下方式获取参数  
            
// public ActionResult PostDemo(string param1, string param2)
            
return View("GetDemo");
        }
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 处理上传文件的 Action
        
/// </summary>
        
/// <param name="file1">与传过来的 file 类型的 input 的 name 相对应</param>
        [AcceptVerbs(HttpVerbs.Post)]
        
public ActionResult UploadFile(HttpPostedFileBase file1)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
// 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
ExpandedBlockStart.gif
ContractedBlock.gif
<%
@ 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"
 
/>
    
&nbsp;
    
<
input 
id
="param2"
 name
="param2"
 
/>
    
&nbsp;
    
<
input 
type
="submit"
 value
="submit"
 
/>
    
</
form
>
</
asp:Content
>
3、处理 JSON 的 Demo
JsonDemo.aspx
ExpandedBlockStart.gif
ContractedBlock.gif
<%
@ 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
>
ExpandedBlockStart.gifContractedBlock.gif    
<
script 
type
="text/javascript"
>
ExpandedSubBlockStart.gifContractedSubBlock.gif        $.ajaxSetup(
{
            cache: 
false
        }
);
        $(document).ready(
ExpandedSubBlockStart.gifContractedSubBlock.gif            
function() {
                $(
'#loading').hide();
                $(
'#btnFind').click(
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
function(event) {
                        event.preventDefault();
                        $(
'#loading').show();
                        $.getJSON(
                            
"/ControllerDemo/JsonResult"// 获取 JSON
ExpandedSubBlockStart.gifContractedSubBlock.gif
                            { name: $('#txtName')[0].value },
ExpandedSubBlockStart.gifContractedSubBlock.gif                            
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"
 
/>
        
&nbsp;&nbsp;
 
<
href
="#"
 id
="btnFind"
>
Find
</
a
>
 
&nbsp;&nbsp;
 
<
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"
 
/>
&nbsp;
Loading
</
span
>
        
<
div 
id
="result"
 style
="margin: 10px 0px"
 
/>
    
</
div
>
</
asp:Content
>
4、上传文件的 Demo
UploadDemo.aspx
ExpandedBlockStart.gif
ContractedBlock.gif
<%
@ 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
你可能感兴趣的文章
小微贷是美团的上坡之路?
查看>>
js 将线性数据转为树形
查看>>
java B2B2C 源码 多级分销Springcloud多租户电子商城系统- 整合企业架构的技术点(二)...
查看>>
微信小程序
查看>>
区块链+金融
查看>>
阿里开发者招聘节 | 面试题14:如何实现两金额数据相加(最多小数点两位)...
查看>>
一些不错的文章
查看>>
Python爬虫常见面试题(二)
查看>>
【译】Web Components简介
查看>>
java生成缩略图类源码
查看>>
java虚拟机
查看>>
Script标签的async和defer
查看>>
JAVA 多用户商城系统b2b2c-kafka处理超大消息
查看>>
java B2B2C源码电子商城系统:服务消费(基础)
查看>>
API 集合
查看>>
我的友情链接
查看>>
a+aa+aaa+aaaa+aaaaa
查看>>
thinkphp_ajax分页实现_无需整理
查看>>
无聊软件-GIT屏幕录制工具_已迁移
查看>>
在论坛如何写好原创技术贴
查看>>