9.MVC框架开发(关于ActionResult的处理)

时间:2023-12-21 12:18:32

1.在Action处理之后,必须有一个返回值,这个返回值必须继承自ActionResult的对象

2.ActionResult,实际就是服务器端响应给客户端的结果

  • ViewResult(返回视图结果)
  • FileResult(二进制文件相应给客户端),FileContentResult继承自FileResult
  • ContentResult(将内容相应给客户端)
  • JsonResult(将对象传递给客户端)
  • JavaScriptResult(将一段JavaScript脚本传递给客户端)
  • PartiaView(返回分布视图)

FileContentResult的应用案例

做一个验证码图片

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging; namespace MvcBookShop.Common
{
public class ValidateCode
{
/// <summary>
/// 生成验证码
/// </summary>
/// <param name="length">指定验证码的长度</param>
/// <returns></returns>
public string CreateValidateCode(int length)
{
int[] randMembers = new int[length];
int[] validateNums = new int[length];
string validateNumberStr = "";
//生成起始序列值
int seekSeek = unchecked((int)DateTime.Now.Ticks);
Random seekRand = new Random(seekSeek);
int beginSeek = (int)seekRand.Next(, Int32.MaxValue - length * );
int[] seeks = new int[length];
for (int i = ; i < length; i++)
{
beginSeek += ;
seeks[i] = beginSeek;
}
//生成随机数字
for (int i = ; i < length; i++)
{
Random rand = new Random(seeks[i]);
int pownum = * (int)Math.Pow(, length);
randMembers[i] = rand.Next(pownum, Int32.MaxValue);
}
//抽取随机数字
for (int i = ; i < length; i++)
{
string numStr = randMembers[i].ToString();
int numLength = numStr.Length;
Random rand = new Random();
int numPosition = rand.Next(, numLength - );
validateNums[i] = Int32.Parse(numStr.Substring(numPosition, ));
}
//生成验证码
for (int i = ; i < length; i++)
{
validateNumberStr += validateNums[i].ToString();
}
return validateNumberStr;
} /// <summary>
/// 创建验证码的图片
/// </summary>
/// <param name="containsPage">要输出到的page对象</param>
/// <param name="validateNum">验证码</param>
public byte[] CreateValidateGraphic(string validateCode)
{
Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), );
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的干扰线
for (int i = ; i < ; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", , (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(, , image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(validateCode, font, brush, , );
//画图片的前景干扰点
for (int i = ; i < ; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), , , image.Width - , image.Height - );
//保存图片数据
MemoryStream stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
//输出图片流
return stream.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}
}
}

ValidateCode

 //创建图片验证码
public ActionResult ValidateImage()
{
ValidateCode validateCode=new ValidateCode ();
string strCode=validateCode.CreateValidateCode();
Session["validateCode"]=strCode;
Byte[] ImageCode=validateCode.CreateValidateGraphic(strCode);
return File(ImageCode, @"image/gif");//类似于Content-Type,表示服务器响应给服务器端的类型
}
//表示返回的是FileContentResult对象,ImageCode表示一个二进制的字节数组,@"image/gif"表示服务器相应给客户端的二进制文件类型。

JsonResult案例,实际是把对象序列化后发给客户端。(这个对象一定要重新构建对象的序列图,实际就是需要new一个新的对象出来)

在用户登陆之后鼠标移动在上面有个悬浮窗显示用户的基本信息

<div id="userinfo" style="display:none">
<table border="">
<tr>
<th>
用户名
</th>
<th>
地址
</th>
<th>
电话
</th>
</tr>
<tr>
<td id="Name"> </td>
<td id="Address"> </td>
<td id="Phone"> </td>
</tr>
</table>
</div>

悬浮层div代码

<script language="javascript" type="text/javascript">
$(function () {
$.get(("/User/ShowUser"), null, function (data) {
if (data != "") {
$("#loginUser").text(data).attr("href", "#").attr("iflogin", "true");
}
}, "text"); $("#loginUser").mouseover(function () { if ($(this).attr("iflogin")) {
$.post("/User/GetUserInfo", null, function (data) {
$("#Name").html(data.Name);
$("#Address").html(data.Address);
$("#Phone").html(data.Phone);
$("#userinfo").css("display", "block");
}, "json");
} else {
$(this).unbind("mouseover"); //将某个事件操作移除
}
}).mouseout(function () {
$("#userinfo").css("display", "none");
}); });
</script>

js代码

public ActionResult ShowUser()
{
ContentResult content = new ContentResult();
if (Session["User"] == null)
{
content.Content = "";
}
else
{
content.Content = (Session["User"] as MvcBookShop.Models.User).Name;
}
return content;
}
[HttpPost]
public ActionResult GetUserInfo()
{
JsonResult js = new JsonResult();
MvcBookShop.Models.User user = Session["User"] as MvcBookShop.Models.User;
//构建新的对象序列图,必须要new
var obj = new
{
Name=user.Name,
Address=user.Address,
Phone=user.Phone
};
js.Data = obj;
//如果这个请求非要是get请求那么需要加下面这段代码
//js.JsonRequestBehavior = JsonRequestBehavior.AllowGet; //允许来自客户端的get请求
return js;
}

注意:在请求JsonResult对象返回的时候,一般默认都采用Post方式请求,如果非要get方式请求,需要去加一段代码:设置:JsonRequestBehavior属性值为:JsonRequestBehavior.AllowGet;

[HttpGet]
public ActionResult GetUserInfo()
{
JsonResult js = new JsonResult();
MvcBookShop.Models.User user = Session["User"] as MvcBookShop.Models.User;
//构建新的对象序列图,必须要new
var obj = new
{
Name=user.Name,
Address=user.Address,
Phone=user.Phone
};
js.Data = obj;
//如果这个请求非要是get请求那么需要加下面这段代码
js.JsonRequestBehavior = JsonRequestBehavior.AllowGet; //允许来自客户端的get请求
return js;
}

Get请求时的代码写法

相关文章