Use __doPostBack() As A Bridge

在进行ASP.NET编程过程中,你必须要面对的问题就是最后不得不使用了很多JavaScript代码,尤其是在打开一个新的”模式(modal )”窗口的时候。

在我的一个工程中,我需要寻求一种方法:将一个modal 窗口中TextBox 的值传递到它的父窗体。从ASP.NET 向JavaScript 传递一个值是很容易实现的,但是从JavaScript 向ASP.NET 传递值就不是那么简单的问题了!可以使用如下方法来解决这个问题。

因为ASP.NET 并不支持modal 窗口,所以我们将不得不使用JavaScript来实现。所以我们给父窗体中的一个Button 增加 attribute 。

Me .Button1.Attributes.Add("onclick", "UpdateQuantityDialogOpen();")

UpdateQuantityDialogOpen是一个JavaScript 方法用于打开一个modal 窗口并且返回一个值。

function UpdateQuantityDialogOpen() {

var retval="";

retval=window.showModalDialog ('updatequantity.aspx','','dialogWidth:400px;dialogHeight:175px;status:no;dialogHide:true;help:no;scroll:no');

if(retval!="" && retval!=null) {

window.execScript("__doPostBack('UpdateQuantity', '" + retval + "')","JavaScript");

}

}
看起来相当的平常, 除了 window.execScript(..)。 它用于调用 __doPostBack() javascript 方法。 只有当你使用特定的服务器控件的时候,这个方法将会出现在你的 JS 中, 例如: LinkButton。

function __doPostBack(eventTarget, eventArgument) 这个方法接收两个参数

在 modal 窗口中,给一个Button增加Attribute
Me .Button1.Attributes.Add("OnClick", "ClosePopUp('txtQuantityOrder');")
被调用的JavaScript方法为:

function ClosePopUp(returnVal) {

//设置返回值

window.returnValue=document.getElementById(returnVal).value;

//关闭

window.close();

}
当我们关闭modal 窗口时,将返回一个值。

在父窗体下增加如下代码:
If Not Page.IsPostBack Then
Response.Write("do")
Else
If Request.Form("__EVENTTARGET") = "UpdateQuantity" Then
Response.Write("返回值为:" & Request.Form("__EVENTARGUMENT"))
End If
End If
通过Request.Form() 可以获取传递到__doPostBack() 方法的值,然后就可以将这个值传递给任意的asp.net方法。This

总结:

我们完成了两件事情:
1. 重新刷新父窗体。
2. 在JavaScript 与 asp.net之间建立了一个桥梁。

Published At
Categories with Web编程
Tagged with
comments powered by Disqus