一:寫個工具類,先引用Newtonsoft.Json.dll,用其序列化對象.
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Newtonsoft.Json;
using System.Web;
namespace ***** .Core.Common
... {
/// <summary>
/// 彈出視窗工具類
/// </summary>
/// <remarks>
/// 實作了彈出視窗傳回對象的封裝方法
/// </remarks>
/// Title: PopUpWindow
public class PopUpWindow
...{
/// <summary>
/// 将對象傳回給調用頁面
/// </summary>
/// <param name="entity">需要傳回的對象執行個體</param>
/// <param name="page">調用此方法的page本身</param>
public static void ReturnObject(Object entity, Page page)
...{
//使用JSON序列化對象
string output = String.Format("var retObj = {0};", JavaScriptConvert.SerializeObject(entity));
//注冊腳本到彈出視窗以傳回序列化後的對象
Type cstype = HttpContext.Current.GetType();
ClientScriptManager cs = page.ClientScript;
//将實體傳回給調用方caller
String csname1 = "CloseScript";
if (!cs.IsStartupScriptRegistered(cstype, csname1))
...{
String cstext1 = String.Format("{0} window.returnValue = {1};window.close();", output, "retObj");
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
}
}
}
二:二:在公共頁某按鈕事件裡設定傳回資料,例如:
protected void Button1_Click1( object sender, EventArgs e)
... {
//建立需要傳回的實體對象
SampleEntity entity = new SampleEntity();
entity.ProjectNo = TextBox1.Text;
entity.ProjectName = TextBox2.Text;
//将對象傳回給調用頁面
PopUpWindow.ReturnObject(entity, this);
////建立需要傳回的實體對象清單
//SampleEntity entity1 = new SampleEntity();
//entity1.ProjectNo = TextBox1.Text;
//SampleEntity entity2 = new SampleEntity();
//entity2.ProjectNo = TextBox2.Text;
//List<SampleEntity> list = new List<SampleEntity>();
//list.Add(entity1);
//list.Add(entity2);
////将對象傳回給調用頁面
//PopUpWindow.ReturnObject(list, this);
}
三:在調用頁放置一用戶端圖檔控件,例如: 然後在用戶端腳本中加入如下代碼即可,建議以模式視窗打開.
< img src ="../images/lookup.gif" onclick ="OnQueryClick()" id ="btnImage" alt ="點選我!" tyle ="cursor: hand" />
//獲得彈出視窗的傳回對象
< script type ="text/javascript" > ...
function OnQueryClick()
...{
var address = "test.aspx";
var parameter1 = "";
var OpenStyle = "dialogWidth:650px;dialogHeight:550px;dialogLeft:200px;dialogTop:150px;center:yes;help:false;resizable:false;status:false";
var returnValue = window.showModalDialog(address,parameter1,OpenStyle);
//分别擷取傳回對象的屬性
if(returnValue != null)
...{
document.getElementById("ctl00$ContentPlaceHolder1$txtProjectNo").value = returnValue.ProjectNo;
document.getElementById("ctl00$ContentPlaceHolder1$txtProjectName").value = returnValue.ProjectName;
}
}
</ script >