常用控制器案例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Text;
namespace Demo2.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
//return View();
//返回一个空的视图
return new EmptyResult();
}
#region 返回脚本文件
/// <summary>
/// JavaScriptResult 的用法(返回脚本文件)
/// http://localhost:11853/home/JavaScriptResultDemo
/// </summary>
/// <returns>返回脚本内容</returns>
public ActionResult JavaScriptResultDemo()
{
//return Content("<script>alert('Test JavaScriptResultDemo!')</script>");
return JavaScript(@"<script>alert('你们好呢!')</script>");
}
#endregion
#region 返回一个json对象
/// <summary>
/// JsonResult的用法(返回一个json对象)
/// http://localhost:11853/home/JsonResultDemo
/// </summary>
/// <returns>返回一个json对象</returns>
public ActionResult JsonResultDemo()
{
var tempObj = new { name = "李白", nickname = "诗仙" };
return Json(tempObj, JsonRequestBehavior.AllowGet);
}
#endregion
#region RedirectResult的用法(跳转url地址)
/// <summary>
/// RedirectResult的用法(跳转url地址)
/// http://localhost:11853/home/RedirectResultDemo
/// </summary>
/// <returns></returns>
public ActionResult RedirectResultDemo()
{
return Redirect(@"http://www.youku.com");
}
#endregion
#region FileContentResult的用法(返回图片)
/// <summary>
/// FileContentResult的用法(返回图片)
/// http://localhost:11853/home/FileContentResultDemo
/// </summary>
/// <returns>显示一个文件内容</returns>
public ActionResult FileContentResultDemo()
{
FileStream fs = new FileStream(Server.MapPath(@"/Images/icon_19.png"), FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[Convert.ToInt32(fs.Length)];
fs.Read(buffer, 0, Convert.ToInt32(fs.Length));
string contentType = "image/jpeg";
return File(buffer, contentType);
}
#endregion
#region FileStreamResult的用法(返回图片)
/// <summary>
/// FileStreamResult的用法(返回图片)
/// http://localhost:11853/home/FileStreamResultDemo
/// </summary>
/// <returns>返回文件流(图片)</returns>
public ActionResult FileStreamResultDemo()
{
FileStream fs = new FileStream(Server.MapPath(@"/Images/icon_19.png"), FileMode.Open, FileAccess.Read);
string contentType = "image/jpeg";
return File(fs, contentType);
}
#endregion
#region FilePathResult的用法(返回图片)
/// <summary>
/// FilePathResult的用法(返回图片)
/// http://localhost:11853/home/FilePathResultDemo/002
/// </summary>
/// <param name="id">图片id</param>
/// <returns>直接将返回一个文件对象</returns>
public FilePathResult FilePathResultDemo(string id)
{
string path = Server.MapPath(@"/Images/" + id + ".jpg");
//定义内容类型(图片)
string contentType = "image/jpeg";
//FilePathResult直接返回file对象
return File(path, contentType);
}
#endregion
}
}
本文来自博客园,作者:.net&new,转载请注明原文链接:https://www.cnblogs.com/wugh8726254/p/12708952.html