1. 程式人生 > >Asp.net MVC Render及Redirect的擴充套件

Asp.net MVC Render及Redirect的擴充套件



namespace
 System.Web.Mvc
{
    
using System;
    
using System.Text;
    
using System.Web.Script.Serialization;
    
using System.Runtime.Serialization.Json;
    
///<summary>/// 對RenderView的擴充套件
    
/// blog:http://chsword.cnblogs.com////</summary>staticpublicclass RenderExtension
    {
        
///<summary>/// 顯示要顯示的文字
        
///</summary>///<param name="c"></param>///<param name="str">文字內容</param>        [Obsolete("僅在Asp.net Mvc Preview2中使用,PV3中已經提供新的方法Content")]
        
staticpublicvoid RenderText(this Controller c, string str)
        {
            c.HttpContext.Response.Write(str);
        }
        
///<summary>/// 將要顯示的物件以JSON返回要客戶端
        
///</summary>///<param name="c"></param>///<param name="data">要傳送的物件</param>        [Obsolete("僅在Asp.net Mvc Preview2中使用,PV3中已經提供新的方法Json")]
        
publicstaticvoid RenderJSON(this Controller c, object data)
        {
           
c.RenderJSON(data, 
null);
        }
        
///<summary>/// 將要顯示的物件以JSON返回要客戶端
        
///</summary>///<param name="c"></param>///<param name="data">要傳送的物件</param>///<param name="contenttype">傳送的Content-Type預設為application/json</param>        [Obsolete("僅在Asp.net Mvc Preview2中使用,PV3中已經提供新的方法Json")]
        
publicstaticvoid RenderJSON(this Controller c, object data, string contenttype)
        {
           
c.RenderJSON(data, contentType, null);
        }
        
///<summary>/// 將要顯示的物件以JSON返回要客戶端
        
///</summary>///<param name="c"></param>///<param name="data">要傳送的物件</param>///<param name="contenttype">傳送的Content-Type為空則預設為application/json</param>///<param name="encoding">編碼方式</param>        [Obsolete("僅在Asp.net Mvc Preview2中使用,PV3中已經提供新的方法Json")]
        
publicstaticvoid RenderJSON(this Controller c, object data, string contenttype, Encoding encoding)
        {
            HttpResponseBase response 
= c.HttpContext.Response;
            
if (!string.IsNullOrEmpty(contenttype))
            {
                response.ContentType 
= contenttype;
            }
            
else
            {
                response.ContentType 
="application/json";
            }
            
if (encoding !=null)
            {
                response.ContentEncoding 
= encoding;
            }
            
if (data !=null)
            {
                
            DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(object));
                sr.WriteObject(response.OutputStream, data);
            }
        }
    }
}