Passing data from a aspx page to a aspx popup - asp.net

Following is the scenario I am facing, I have a aspx page in which I have added my ascx user control, I also have a <a href control which call a js function to open a aspx popup.
when I open the popup, I need to send the data present in the ascx control to my popup. can you please guide me what method can I use to achieve this other than using session, as the data can be updated in many different places hence maintaining in session will be difficult.
Thanks

try with these syntaxe ( RegisterStartupScript + window.open)
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "newWindow", "window.open('Test.aspx?ID=" + _cId + "','_blank','status=1,toolbar=0,menubar=0,location=1,scrollbars=1,resizable=1,width=30,height=30);", false);

You said that you are using a js function to open the aspx popup.
then it is simple.
1. Read the Data from the controls of the User control by using javascript
var variable1 = document.getElementByID("ControlId").value;
var variable2 = document.getElementByID("ControlId").value;
2. Pass this data as query string to the next page
window.open("http://www.w3schools.com?id=" + variable1 + "&name=" + variable2);
You can read this data from querystring from the next page

If you cant sent data as querystring , can try some other ways
1. Try to post the form to the other page using target="_blank".
we can dynamically change the form action if needed.
OR
2. Make use of the window.opener object from the popup to read the data from controls the opener page.
var variable1 = window.opener.getElementById("ControlId").value

Create a hidden variable in your ascx.
<asp:HiddenField runat="server" ID="hdnId" />
On page load of ascx set the value to be sent to the hidden variable
protected void Page_Load(object sender, EventArgs e){
hdnId.Value = <value to be sent to pop-up>;
}
Register a ajax manager in the code behind.
protected override void OnInit(EventArgs e)
{
RadAjaxManager.GetCurrent(this.Page).ClientEvents.OnRequestStart = "ajaxMngr_RequestStart;";
base.OnInit(e);
}
In the ajaxMngr_RequestStart() JS
function ajaxMngr_SA_RequestStart(sender, args) {
var oPatId = "<%=hdnSendPatId.Value %>";
//add code to open the pop-up, add oPatId as part of the URL
}
}
I use Telerik, which makes helps a lot in managing pop-ups. Let me know, if this helps.
Cheers!

Related

RenderControl in asp.net not getting the html i added into that control using JQuery

I am using a jQuery editor and when the user hits the submit button i put the content into asp.net Panel control as html and then when i render this Panel the html i added is not
retrieved.
function MoveData() {
var sHTML = $('#summernote_1').code();
// dvFrontPageHtml is asp.net Panel
$('[id*=dvFrontPageHtml]').html(sHTML);
setTimeout(function () {
javascript: __doPostBack('ctl00$ctl00$ContentPlaceHolderBody$ContentPlaceHolderBody$lnkSave', '');
}, 10000);
return false;
}
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
dvFrontPageHtml.RenderControl(htmlWriter);
string Message = sb.ToString();
The message does not returning the html added.
I dont want to use jQuery ajax call as of now.
Any suggestions
without seeing all the relevant code its hard to pinpoint the problem.
but im pretty sure you are trying to find an ASP.net control by its serverside ID from clientside.
dvFrontPageHtml is the Controls ID by which asp.net identifies it, and unless you explicitly tell ASP.Net otherwise, it will generate a different ID for the control to be used by scripts at clientside
you need to retrieve the panel's clientside ID thats being generated for it by asp.net
you do it by a preprocessor directive <%=dvFrontPageHtml.ClientID%>:
$('[id*=<%=dvFrontPageHtml.ClientID%>]').html(sHTML);
alternatively, if you want the clientside ID to be same as the serverside ID, you can set the control's attribute ClientIDMode="Static".
UPDATE:
from your comment it seems the problem is elsewhere. what comes to mind, is that RenderControl() takes the control as it was when sent to the client in the Response. but the control is not being submitted to the server in next Request, so you will not be able to retrieve its altered html.
what you can do as a workaround, is hook into ASP.NET's build in postback mechanism, and submit the panel's html as a custom event argument:
for the example, lets assume this is our html:
<asp:Panel ID="dvFrontPageHtml" runat="server" ClientIDMode="Static">test</asp:Panel>
<asp:Button ID="BT_Test" runat="server" Text="Button"></asp:Button>
this will be our javascript:
$(function(){
// add custom event handler for the submit button
$("#<%=BT_Test.ClientID%>").click(function (ev) {
//prevent the default behavior and stop it from submitting the form
ev.preventDefault();
//alter the panels html as you require
var sHTML = $('#summernote_1').code();
$('[id*=dvFrontPageHtml]').html(sHTML);
//cause a postback manually, with target = BTCLICK and argument = panel's html
__doPostBack('BTCLICK', $('[id*=dvFrontPageHtml]').outerHTML());
});
});
and here we capture the postback on serverside:
//we monitor page load
protected void Page_Load(object sender, EventArgs e)
{
string Message;
//check if its a postback
if (IsPostBack)
{
//monitor for our custom target "BTCLICK"
if (Request.Form["__EVENTTARGET"].CompareTo("BTCLICK") == 0)
{
// retrieve the panels html from the event argument
Message = Request.Form["__EVENTARGUMENT"];
}
}
}

Access dynamically generated control from code behind

I load a piece of html which contains something like:
<em> < input type="text" value="Untitled" name="ViewTitle" id="ViewTitle" runat="server"> </em>
into my control. The html is user defined, do please do not ask me to add them statically on the aspx page.
On my page, I have a placeholder and I can use
LiteralControl target = new LiteralControl ();
// html string contains user-defined controls
target.text = htmlstring
to render it property. My problem is, since its a html piece, even if i know the input box's id, i cannot access it using FindControl("ViewTitle") (it will just return null) because its rendered as a text into a Literal control and all the input controls were not added to the container's control collections. I definitely can use Request.Form["ViewTitle"] to access its value, but how can I set its value?
Jupaol's method is the prefer way of adding dynamic control to a page.
If you want to insert string, you can use ParseControl.
However, it doesn't cause compilation for some controls such as PlaceHolder.
Your process is wrong, you are rendering a control to the client with the attribute: runat="server"
This attribute only works if the control was processed by the server, you are just rendering as is
Since your goal is to add a TextBox (correct me if I'm wrong), then why don't you just add a new TextBox to the form's controls collection???
Something like this:
protected void Page_Init(object sender, EventArgs e)
{
var textbox = new TextBox { ID="myTextBoxID", Text="Some initial value" };
this.myPlaceHolder.Controls.Add(textbox);
}
And to retrieve it:
var myDynamicTextBox = this.FindControl("myTextBoxID") as TextBox;
I have created several working examples and they are online on my GitHub site, feel free to browse the code

How to access values of previous page at client-side?

I have a page and clicked on the button there it will open a new page containing some text boxes, user fill all the text boxes and clicked the button now first page open again and the question is : How can I get the vales of text boxes on the current page using both server-side and client-side
There is a restrictions to use of :
- Cross-paging
- Cookies
- Sessions
- Query strings
Server-side approach:
An alternate approach is to use Server.Transfer method.
On the current page:
protected void Transfer_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
Server.Transfer("destination.aspx");
}
}
On the destination page:
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox textBox = PreviousPage.FindControl("Parameter")
as TextBox;
if (textBox != null)
{
string parameter = textBox.Text;
Parameter.Text = parameter;
}
}
}
But Server.Transfer does come with disadvantages. The most serious is that the URL in the browser does not change. The browser still believes it has posted back and received content for the first web form, so history and book-marking suffer.
Client-side approach:
In real world I don't recommend to use this solution, this is only a workaround.
In two words: use window.name property on the client side. This property is available across page reloads it is a sort of session.
For more information see:
What’s in a window.name?
window.name Transport
Hope, this helps.
If you are using the PostBackUrl property of the button on the submitting page, you can access the controls for the "previous page" from the action page by using the following:
Dim txtBox as TextBox
txtBox = CType(Page.PreviousPage.FindControl("MyTextBox"), TextBox)
Then you'll have access programmatically to all of the properties and data for that control.
Use the cache if you can't use the Session, Querystring, Cookies and Cross Page posting.
If it is simple/primitive data, then you can go for the ViewState. Or Cache is a better option.
One more option is to have a Page level public variables, set the required values and redirect to the page for further processing.(This is not a good approach to follow)

How to call javascript in a child page's onload event

I have an ASP.net application with an aspx page.
In Page_Load event of the aspx page, I'm handling some code which is based on the value of a hidden variable from the javascript(assigning result of javascript to hidden variable).
I am calling the javascript in Page_Load of the child page, and in the immediate statement, I'm making use of the hidden variable value for processing. When I access hidden variable value, I'm getting default value only.
Please suggest me any of handling the scenario. I need to execute the javascript and get the result into the hidden variable. Both in need to occur in Page_Load event only.
Hidden Variable declaration:
<asp:HiddenField runat='server' ID='hdnDate' Value='0' />
Javscript:
function getCDate() {
var nowDate = new Date();
var curr_month = nowDate.getUTCMonth();
curr_month ++;
var dt = curr_month + "/" + nowDate.getUTCDate() + "/" +nowDate.getFullYear()+ " " + nowDate.getUTCHours()+":" +nowDate.getUTCMinutes()+":" +nowDate.getUTCSeconds();
document.getElementById("ctl00_ContentPlaceHolder1_hdnDate").value = dt;
return true;
}
Page_Load method in code behind file:
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "getCDate();", true);
DateTime dt=Convert.ToDateTime(hdnDate.Value);
dt.AddDays(10); //getting error here because dt contains01/01/0001
}
You cannot call javascript in Page_Load. It is client side thing so should come from browser only. You can check if page is postback using IsPostBack property of Page object like this:
if(IsPostBack)
{
//this is coming from browser so you javascript might have been
//called and proper value set in hidden field.
}
Javascript is run on the client side, so can't run in the Page_Load event on the Server.
From the looks of your code, I'm pretty sure you don't need javascript, you can just put the value into a SessionVariable as:
Session.Add("DateRendered", DateTime.Now.AddDays(10).ToString("MM/dd/YYYY"));
And then retrieve it later. ASP.net takes care of storing it in the Request/Response.
RegisterStartupScript will register your block of script for the next page load.
if you just want some value to be transferred to .cs page write a static method on the .cs and call it from javascript using PageMethods.MethodName();

ASP.NET WebForms + Postback then open popup

I have a LinkButton that has to postback to perform some logic.
Once it is finished, instead of loading the page back up in the browser, I want to leave it alone and pop open a new window.
So far, the best idea I've had is to put the LinkButton in an UpdatePanel, and have it render some JavaScript out when it reloads, yet I think that is totally hacky. Also, if I recall right, JavaScript within a update panel won't run anyways.
Any other ideas?
Use LinkButton.PostBackUrl to set a different page to POST to, and some client script to get a new window (and the old target restored so that future postbacks work normally). The 2nd page can use PreviousPage to get access to any needed state from the original page.
<script runat="server">
void lnk_Click(object sender, EventArgs e) {
// Do work
}
</script>
<script type="text/javascript">
var oldTarget, oldAction;
function newWindowClick(target) {
var form = document.forms[0];
oldTarget = form.target;
oldAction = form.action;
form.target = target;
window.setTimeout(
"document.forms[0].target=oldTarget;"
+ "document.forms[0].action=oldAction;",
200
);
}
</script>
<asp:LinkButton runat="server" PostBackUrl="Details.aspx" Text="Click Me"
OnClick="lnk_Click"
OnClientClick="newWindowClick('details');" />
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
// Do some server side work
string script = "window.open('http://www.yahoo.com','Yahoo')";
if (!ClientScript.IsClientScriptBlockRegistered("NewWindow"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(),"NewWindow",script, true);
}
}
One thing you could try is to have your LinkButton OnClick event do its processing, then register a Page.ClientScript.RegisterStartupScript with the popup code, which will put some Javascript into the tag to fire off after the page loads. This should launch your new window after the processing completes.
EDIT: Reading your comment, I believe you can still use this approach, have your results stored in a session variable, and then have the popup page pull the results from there.

Resources