How to access a parent element from iframe using c#? - c#

I am working on a website in asp.Net, and i am using iframe to load a separate page.
The separate page named Districting.aspx, includes an asp button, which onClick(), calls a function in c#, named DoneClicked().
This is the asp button control:
<asp:Button ID="LinkButtonDone" CssClass="button button-yellow" runat="server" OnClick="DoneClicked" Text="Done" />
In code behind, the DoneClicked function:
protected void Doneclicked(object sender, EventArgs e)
{
// Some code here
// Calling a function from Default page
}
What I need to do is at the end of DoneClicked function, a function from the Default.aspx page must be called.
So how can I access a function from Default.aspx.cs in the iframe page code behind?
Thanks:)

Try Below It Worked for me
In Code Behind
protected void Doneclicked(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptid", "window.parent.location.href='ParentPageName.aspx';", true);
}

You can't access it directly (at least not in an advisable fashion).
You should abstract out the common code from Default.aspx into a class somewhere that can be used by both pages.

You can not do that direct, but you can do it indirect using javascript.
So you make a hidden button on the default page that can call the DoneClicked function as:
<div style="display:none">
<asp:Button ID="Done" runat="server" ClientIDMode="Static" OnClick="DoneClicked " />
</div>
and inside the iframe where Districting.aspx is loaded, you can call the "DoneClicked" by clicking the button using javascript as:
<script type="text/javascript">
window.parent.document.getElementById('Done').click();
<script>
Note that the ClientIDMode="Static" because from the other page you can not know what is the rendered id, so keep it static. If you do not use dot net 4 that have the static id, then you need to also use javascript to send the rendered id to the page, or some other way to locate the button.
Also note the window.parent. that "can see" from the iframe the DOM structure of the controls of the page that contains the iframe.

Related

Using ASP.NET to Hide an HTML Div

I am using ASP.NET for a web page in order to make some server calls that involve looking up user organization information. Based on that information, we need to either hide or display a div. In the header I have a C# function that definitely runs. I have tried the following lines to hide the div.
divID.Style.Add("display","none");
and
divID.Visible = false;
In the body, I am currently using an asp:Panel that runs at server and contains the id "divID". No matter what I do, I can't get the div to hide (without manually putting the styling in). I tried putting the scripts before and after the body, and it didn't make a difference. Any suggestions on the best way to do this would be appreciated.
EDIT:
Here is the C# initiating code.
<script runat="server" language="C#">
void getUserInfo(Object sender, EventArgs ev){
The rest of the C# code is irrelevant, but the relevant line shown above is definitely being run.
The HTML portion looks something like this.
<asp:Panel runat="server" id="divID" style="width:200px; height:130px; ">
<div style="text-align:center">Test Data</div>
</asp:Panel>
C# code is always compiled and run from the server-side, and so cannot impact the state of a page once rendered unless you use postbacks or callbacks. If you want to change the visible state of a control on the client-side, you will need to use Javascript on the client side (possibly triggered by a button click) to show and hide the control.
As an example, check out the solution at the link below.
https://forums.asp.net/t/1603211.aspx?Show+hide+div+on+button+click+without+postback
<script type="text/javascript">
function ToggleDiv(Flag) {
if (Flag == "first") {
document.getElementById('dvFirstDiv').style.display = 'block';
document.getElementById('dvSecondDiv').style.display = 'none';
}
else {
document.getElementById('dvFirstDiv').style.display = 'none';
document.getElementById('dvSecondDiv').style.display = 'block';
}
}
</script>
<asp:Button ID="btn" runat="server" Text="Show First Div"
OnClientClick="ToggleDiv('first');return false;" />
<asp:Button ID="Button1" runat="server" Text="Show Second Div"
OnClientClick="ToggleDiv('second');return false;" />
<br />
<div id="dvFirstDiv" style="display: none;">
First Div
</div>
<div id="dvSecondDiv" style="display: none;">
Second Div
</div>
In the header I have a C# function that definitely runs.
If you're talking about the HTML page header - no, it definitely not running. C# code is executed only server side.
Based on your post, I'm assuming we're talking WebForms here and yo have a script block in your aspx file. While this is fine, I recommend placing the server-side code into a code behind file.
So all you need to do is to add a handler for the PreRender phase of the page life cycle and place your logic for showing/hiding the div in there.
public void Page_Prerender(object sender, EventArgs e)
{
divID.Visible = false;
' OR
'divID.Style.Add("display","none");
}
Note that setting the Visible property of a WebForms control excludes the control from rendering to the page, whilst setting display: none renders it as HTML but it isn't displayed on the page.
Try in backcode: divID.Controls.clear();
This worked for me.

Adding OnClick event to ASP.NET control

i would like to create OnClick event for my panel. So far now the most of the google results look more or less like this: adding onclick event to aspnet label. Is there any way, to call codebehind function from javascript or panel attributes? Because I would like to Redirect user to a new page and before that save some information in ViewSTate or Sessionstate. Any suggestions?
In your java script method raise a __dopostback call to a Server side method.
<script type="text/javascript">
function YourFunction()
{
__doPostBack('btnTemp', '')
}
</script>
Where btnTemp is a server side button, so write a onClick event of this button on server side, where you can do the processing and then redirect to other page.
You can have a good understanding of dopostback at DoPostBack Understanding
My aspx page is like:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script type="text/javascript">
function CallMe() { __doPostBack('btnTemp', '') }
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="btnTemp" runat="server" Text="Test" onclick="btnTemp_Click" />
<div> <asp:Label ID="Label1" runat="server" Text="Label1"></asp:Label>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label></div>
</form>
</body>
And my Server Side code is as:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Attributes.Add("onClick", "CallMe();");
}
protected void btnTemp_Click(object sender, EventArgs e)
{
}
Thats the code that I have written, I haven;t included the using statement, Page directive etc in above code.
There is a PostBackUrl property on a ASP.NET Button, you could render the button as normal then postback to a different page - this is where your OnClick method would need to be declared.
I would strongly recommend against posting back to the same page then doing a Response.Redirect(), consider the traffic. The browser requests the page, posts back then is sent a HttpRedirect and then navigates to the new page. With the method I have outlined above this is not required and the browser has to make one request less (meaning the message doesn't have to be sent or the page rebuilt on the server) and is a significant performance benefit.

Is it possible to apply an onclick() event to a span tag?

To make sure that an event handler is written properly, I generally have Visual Studio generate the event for me. However, I can't find a way to do this with a div and I've tried typing it out myself to no avail. Is this even possible without writing any javascript? (I saw similar questions, but couldn't seem to find anything that fit my needs).
Edit: Basically I have a logoff div disguised to the user as a button. When they click it, I want the following to happen:
protected void LogOff_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Session.Abandon();
//This will clear the authentication cookie
HttpCookie myHttpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, "");
myHttpCookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(myHttpCookie);
//This will clear the session cookie (not required for my application but applying to be safe)
HttpCookie myHttpCookie2 = new HttpCookie("ASP.NET_SessionId", "");
myHttpCookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(myHttpCookie2);
FormsAuthentication.RedirectToLoginPage();
}
Here's where I call this event:
<span class="MenuItem" runat="server" onclick="LogOff_Click">Log Off</span>
Your LogOff_Click is fine. However, you need to modify your markup. Apply the onserverclick event to the <a> tag instead of <span>. In your case, try the following:
<span class="MenuItem">Log Off</span>
Description
The div element supports the javascript event onclick so you can do it.
You can check if a html element supports a given event by looking on w3c shools tag definition.
It is not clear to me what you exactly mean. You can do many things using javascript on the client side. onclick is javascript but you can do things like redirects using the serverside (Postback on ASP.NET Webforms) too. Things you do with javascript are, without doing ajax, not noticeable by the server, cause javascript get handled by the browser.
Check out my sample and this jsFiddle Demonstration
Sample for the <div> tag
Html
<div onclick="alert('hello');">hello world</div>
More Information
jsFiddle Demonstration
w3c shools tag definition
If you wanted to stay in ASP.NET, you could use a Panel control and do something like this:
Markup
<body>
<form id="form1" runat="server">
<div>
<asp:Panel runat="server" ID="pan1">click here</asp:Panel>
</div>
</form>
</body>
Code Behind
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
pan1.Attributes.Add("onclick", "javascript:alert('here');return false;");
}
}
You're still writing JavaScript, but you're staying with the ASP.NET controls and the ASP.NET way of setting client-side events.
I actually prefer the method of dknaack and Silvertiger -- put the event in the client side code (preferably a javascript file instead of inline).
Standard DOM and CSS will allow this
<div style="cursor:hand;" onclick="this.document.location.href ='http://www.google.com';">
My content
</div>
should do the trick
Not sure what exactly you intend to do. When the onclick event is triggered, you would need a handler to be called, when the event is triggered. This is done via Javascript.
You can do a form submit in the JavaScript, or trigger an Ajax callback in the Javascript, to interact with your .NET application.
Answering the original question, onclick event can be triggered via <div> tag. Make sure you test against Internet Explorer 7/8 (compatibility mode) as not all events work in IE 7/8. It should be okay in Firefox, Chrome and IE9. Save this in a file and experiment.
<html>
<head>
<script type="text/javascript">
function JSFn()
{
//you can use the div ID if needed: var id = document.getElementById('div_id');
alert("JSFn was called");
//Can do form submit or Ajax callback to interact with .NET app
}
</script>
</head>
<body>
<div>
<a id="anchor1" href="javascript:JSFn();">Make a clickable link here, you can use onclick and href='#' </a>
</div>
<div id="div_id2" onclick="JSFn()">Just click here </div>
</body>
</html>

How to make an html element contain text when an ASP:Button is pressed?

I've got a DIV which contains some text in it.
Ive also got an asp:Button, which when pressed I would like to retrieve this text. However, it appears that as soon as I press the button, the DIV's contents is reset - most likely due to postback.
The DIV has got runat=server". Does anyone have any idea as to what may be done to make this DIV retain its contents on pressing the button? The data is manipulated countless times before the button is pressed, so I would like to try avoiding updating a Session every time.
Try something like this:
getText = function(){
alert($("#<%=Panel1.ClientID%>").text());
return false;
}
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:Button ID="Button1" runat="server" OnClientClick="return getText();" ... />
You can also try this:
$("#<%=Button1.ClientID%>").click(function(){
alert($("#div1").text());
return false;
});
One way would be grabbing button click event in your makrkup, store your DIV content in a hidden field, then fire postback manually in your button click.
Try using an asp:Panel. It renders as a DIV and you have access to all of its properties at all points in the page life cycle.
another way is to use Ajax. specifically - updatepanel control
You can store you DIV content in a hidden field by calling a JavaScript function in onClientClick event of the button - it will execute just before OnClick event, before postback. This way, there's no need to fire postback manually.
Let's say you have one div, one hidden field and button with onClientClick and OnClick events. You use simple JavaScript function for the job:
<div id="myDiv" runat="server" ></div>
<asp:Button ID="btnGetDiv" runat="server" Text="Get div value" OnClick="getValueOnServer" OnClientClick="setHiddenFieldF()"/>
<asp:HiddenField ID="hf" runat="server" />
<script type="text/javascript">
function setHiddenFieldF() {
var nevValue = document.getElementById('<%= myDiv.ClientID %>').innerHTML;
document.getElementById('<%= hf.ClientID %>').value = nevValue;
}
</script>
Then, on the server, just use the value of the hidden field.
You can't read your DIV's content because it is not send to the server in the postback. Only values of form elements (<input>, <textarea>, <select>, etc.) are send.
If you really want to read DIV's content, you can copy it to the hidden input (as wrote Kavousi).
Just add hidden field to your page:
<asp:HiddenField ID="hidden" runat="server" />
And then in code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Page.Form.Attributes["onsubmit"] = string.Format(#"$(""#{0}"").val($(""#{1}"").html());", hidden.ClientID, div.ClientID);
}
}
(div is your div's name).
You can then read div's content by reading hidden.Value.

How to open the redirected page from Iframe to open in the parent window in ASP.NET?

I have an asp.net page that contains an Iframe embedded with some data and a ImageButton. On ImageButton click event (server side) I have Response.Redirct:
Response.Redirect("results.aspx");
This always open the results.aspx in iframe. I want that results.aspx should always open in the parent window. I tried the following till now but none worked:
Response.Redirect("<script language='javascript'>self.parent.location='results.aspx';</script>");
Response.Redirect("javascript:parent.change_parent_url('results.aspx');");
As responded by Rifk, I add the ClientScriptManager.
.aspx has this entry:
<asp:ImageButton ID="ImageButton_ok" ImageUrl="~/images/ok.gif"
OnClick="btnVerify_Click" OnClientClick="ValidateFields()"
runat="server" />
Code behind in Page_Load():
ClientScriptManager cs = Page.ClientScript;
StringBuilder myscript = new StringBuilder();
myscript.Append("<script type=\"text/javascript\"> function ValidateFields() {");
myscript.Append("self.parent.location='default.aspx';} </");
myscript.Append("script>");
cs.RegisterClientScriptBlock(this.GetType(), "ButtonClickScript", myscript.ToString());
btnVerify_Click has the main business logic. How will I stop OnClientClick() to fire if there my business logic fails? or, how can I fire when server side code is successfully executed?
Response.Redirect will only effect the page in the iFrame if that is the page that is doing the redirect on the server side. You want to run some javascript within that iFrame that will redirect the parent, as you have in your second example. In order to run the script, you shouldn't be using Response.Redirect(), but rather you should be registering client script.
See the following link as to how to register client script in your code in ASP.Net 2.0 -
Using Javascript with ASP.Net 2.0
For example, you would add something similar to this at the end of your event that handles the ImageButton Click:
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "myUniqueKey",
"self.parent.location='results.aspx';", true);
I have an asp.net page that contains an Iframe embedded with some data and a buttons. On button click event (server side) I have Response.Redirct, but i need to close the Iframe and load the parent page.adding the below mentioned script solved the issue.
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "myUniqueKey", "self.parent.location='results.aspx';", true);
Thanks Rifk for the solution. Here is the code for those who have similar issue:
In aspx file, I have defined a new JS function Redirection(). ValidateFields() function will do some client side validations.
<head runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
function ValidateFields()
{
alert ("Some client side validations!!");
}
function Redirection()
{
self.parent.location="http://www.google.com";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Content - In IFrame</h2>
<asp:CheckBox ID="chkValid" runat="server" />
<asp:ImageButton ID="ImageButton_FillW8Online" ImageUrl="~/images/expand.gif"
OnClick="btnVerify_Click" OnClientClick="return ValidateFields()"
runat="server" style="height: 11px" />
</div>
</form>
</body>
in code behind, I have very simple code that registers clientscriptblock after doing some server side validations. I required that the redirection to happen only if the server side validation is successfull.
bool isValid = false;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnVerify_Click(object sender, EventArgs e)
{
//do some validations
isValid = chkValid.Checked;
if (isValid)
this.Page.ClientScript.RegisterClientScriptBlock(typeof(string), "", "Redirection()", true);
}
You can try this:
Response.Write("<script>window.open('page.aspx','_parent');</script>");
Regards.
Response.Clear();
Header.Controls.Add(new LiteralControl(#"
<script type=""text/javascript"">
top.location = ""/Logout.aspx"";
parent.location = ""/Logout.aspx"";
</script>
"));
If you just want to open a website directly "over" the current page with your iframe (not new tab or window), then you don't need code-behind.
ie:
<asp:LinkButton ID="lnkGeneralEnq" runat="server" OnClientClick="OpenOverFrame();"><strong>click this link</strong></asp:LinkButton>
and a single line Java script bit of code in your ASPX page...
function OpenOverFrame() {
window.open('http://mywebsite.com','_parent');
}

Categories

Resources