I am trying to call a script in an IFrame from the parent page from the code behind. The C# I use to call the function:
protected void Page_Load(object sender, EventArgs e)
{
...
string scr = "document.getElementById('mapframe').contentWindow.addPoint(0, 0);"
ClientScript.RegisterStartupScript(GetType(), Guid.NewGuid().ToString(), scr , true);
}
The iFrame's HTML:
<iframe name="mapframe" id="mapframe" src="Map.html" style="width:100%;height:360px;"></iframe>
And the Javascript in the IFrame:
function addPoint(lat, lon) {
var myLatlng = new google.maps.LatLng(lat, lon);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Hit"
});
}
However, this causes this error: "Unable to get property 'addPoint' of undefined or null reference". What is causing this error? I have checked to ensure that contentWindow is not null.
The problem is likely that your iframe is not loaded when you try to call that function
Try the following
document.getElementById('mapframe').onload = function() {
// I prefer frames.mapFrame.addPoint();
document.getElementById('mapframe').contentWindow.addPoint(0,0);
}
Or even
<iframe
name="mapframe"
id="mapframe"
src="Map.html"
style="width:100%;height:360px;"
onload="this.contentWindow.addPoint(0,0)"></iframe>
once the iframe is loaded then after you can call the function add point.
or you can put the call of this function in onload event
Related
I am working on application where i want to pass data from one to another using Cache. On First page which is an .aspx page iI have a textbox control and one button Control. On button control click event i have written following code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (!string.IsNullOrEmpty(txtName.Text.Trim()))
{
Cache["Name"] = txtName.Text;
Response.Redirect("Test.html");
}
}
catch (Exception ex)
{
throw (ex);
}
}
Now on the Target page i.e Test.html i have written following code to get cache value
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//var name = GetParameterValues('ID');
//var name = '<%= session.getAttribute("Name") %>';
var name = (string)["Name"];
alert(name);
});
but this code is not working. Please help me.
you should get cache value from server side not client (Javascript)
So it should be:
var name = '<%=Cache["Name"] %>';
btw. your test.html should be *.aspx site that way asp engine can parse it.
Or if it's completely different app to pass data you can not use cache !
One way to do this POST or GET methods.
I've looked at responses to similar questions like this, but since I'm new to ASP.NET, I'm not sure they apply to exactly what I'd like to do.
I have a button on a .aspx page that once pressed, I'd like its click event to call a JavaScript function I have on my MasterPage to show a modal popup.
I'd like the click event to also be able to update the content of the modalpopup. Is this possible by putting .aspx labels in the modalpopup and setting their text from code-behind?
Here is the code for my JavaScript modalpopup:
<script>
// Demo modal
function openModal() {
$.modal({
content: '<p>This is an example of modal window.</p>' +
'<p>Test text:</p>' +
'<ul class="simple-list with-icon">' +
' <li>Sample Text</li>' +
'</ul>',
title: 'Example modal window',
maxWidth: 500,
buttons: {
'Open new modal': function (win) { openModal(); },
'Close': function (win) { win.closeModal(); }
}
});
}
</script>
Currently this popup is shown when someone clicks a link that has an "openModal" onclick event. But how can I have it up after a .aspx button has done a postback, and how can I dynamically change its text?
I'd like to be able to just have a modalpopup function on my MasterPage, that any other page could populate with content to show any messages that they need.
I also wanted to note that this is being done on a postback, in case any responses are based on the page is not being refreshed.**
C#:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) {
if ((Session("myButtonWasClicked") != null)) {
string content = "<p>This is an example of modal window.</p>";
//make sure to escape any characters that need escaping
StringBuilder sb = new StringBuilder();
sb.Append("<script type='text/javascript'>openModal('" + content + "');</script>");
Page page = HttpContext.Current.CurrentHandler;
ClientScriptManager cs = page.ClientScript;
cs.RegisterClientScriptBlock(typeof(Reports), "modulFunction", sb.ToString, false);
Session("myButtonWasClicked") = null;
}
}
}
//Don't forget to assign this event to your button
protected void btn_Click(object sender, EventArgs e)
{
Session("myButtonWasClicked") = 1;
}
VB.NET:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If IsPostBack Then
If Not IsNothing(Session("myButtonWasClicked")) Then
Dim content As String = "<p>This is an example of modal window.</p>" 'make sure to escape any characters that need escaping
Dim sb As New StringBuilder
sb.Append("<script type='text/javascript'>openModal('" + content + "');</script>")
Dim page As Page = HttpContext.Current.CurrentHandler
Dim cs As ClientScriptManager = page.ClientScript
cs.RegisterClientScriptBlock(GetType(Reports), "modulFunction", sb.ToString, False)
Session("myButtonWasClicked") = Nothing
End If
End If
End Sub
Protected Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
Session("myButtonWasClicked") = 1
End Sub
Where Reports is the type of a class or page your code is in.
Your Script:
<script>
// Demo modal
function openModal(param) {
$.modal({
content: param,
title: 'Example modal window',
maxWidth: 500,
buttons: {
'Open new modal': function (win) { openModal(); },
'Close': function (win) { win.closeModal(); }
}
});
}
</script>
Try something like:
Response.Write("<script> openModal(); </script>");
Or if you are using ScriptManager on the page then you can also try using this:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "CallFunction", "openModal();", true);
Using jQuery I'm trying to get the id of control, which I clicked (radiobutton). I read this question and tried almost everything from there:
alert($(this).get(0).id);
alert($(this).id);
alert($(this).attr('id'));
alert(this.id);
But I'm always getting: Undefined
I just don't understand what I'm doing wrong.
UPDATED:
Radiobuttons is generated dynamically in code behind by C#:
controlToReturn = new RadioButton
{
ID = controlId
};
((RadioButton)controlToReturn).Text = text;
((RadioButton)controlToReturn).Checked = Convert.ToBoolean(Convert.ToInt32(value));
((RadioButton)controlToReturn).GroupName = groupName;
((RadioButton)controlToReturn).CssClass = cssClass;
((RadioButton)controlToReturn).Attributes.Add("runat", "server");
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show();");
and function in ASPX:
<script type="text/javascript" language="javascript">
function Show() {
if ($(this).cheked = true) {
console.log(this);
alert($(this).get(0).id);
alert($(this).id);
alert($(this).attr('id'));
alert(this.id);
}
}
</script>
I know radiobutton has id, I checked generated HTML.
Your problem is this has no context within your function and is in fact the window itself.
You would need to modify both the output html to provide context as an argument:
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show(this);");
and change the function Show:
function Show(el) {
/* for jQuery use $(el) */
if(el.checked) {
alert(el.id);
}
}
C#:
((RadioButton)controlToReturn).Attributes.Add("onclick", "Show(this);");
JavaScript:
function Show(radio) {
if (radio.checked) {
alert(radio.id);
}
}
To attach a click-listener and alert the ID, your code would look something like this:
$(function () {
$("input[type='radio']").on("click", function () {
alert(this.id);
});
});
A working demo: http://jsfiddle.net/SSBnV/1/
I have a Image Button declared as,
<div>
<asp:ImageButton ID="btnDoWork" runat="server" ImageUrl="/_LAYOUTS/1033/IMAGES/row.png" ValidationGroup="Page" />
</div>
<div>
<asp:RequiredFieldValidator runat="server" ID="reqName" ControlToValidate="txtEmail" ValidationGroup="Page" ErrorMessage="enter a email" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ValidationExpression="^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$" ControlToValidate="txtEmail" ValidationGroup="Page" ErrorMessage="enter a email" />
</div>
within a update panel,
now in code behind I am doing something like this,
btnDoWork = (ImageButton)this.control.FindControl("btnDoWork"); //this code is in childcontrols method
btnDoWork.Click += new ImageClickEventHandler(btnDoWork_Click);
then
protected void btnDoWork_Click(object sender, ImageClickEventArgs e)
{
//Process a bit of code and at end,
this.Page.Unload += new EventHandler(Page_Unload_MessageBox);
and then in button click event,
public static void Page_Unload_Page_Unload_MessageBox(object sender, EventArgs e)
{
System.Globalization.CultureInfo _culture = Thread.CurrentThread.CurrentUICulture;
StringBuilder sb = new StringBuilder();
sb.Append("<script language=\"javascript\">");
sb.Append("$('body').append(\"<div id='M'><span id='text'>" +
SPUtility.GetLocalizedString("$Resources:abc", "def", (uint)_culture.LCID) +
"</span><br/><div id='BB' onclick='return BB();'><a href='' onclick='return BB();'>" +
SPUtility.GetLocalizedString("$Resources:OK", "def", (uint)_culture.LCID) +
"</a></div></div>\");");
sb.Append("function BB() { $('#M').remove(); $('#E').remove(); return false; }");
sb.Append("function dM(){ var browser = navigator.appName; if (browser == 'Netscape') { $('#M').css({ 'top': '5%' }, 500); } }");
sb.Append("</script>");
// Write the JavaScript to the end of the response stream.
HttpContext.Current.Response.Write(sb.ToString());
Now if I put email address I get error while when it tries to Response.Write I think, I wonder what alternative is there, e.g. can I use triggers in update panel or any other event or something..
here's the error I am getting now,
Note: I changed all variable names so don't get confused if something doesn't match
The message is very clear, you can not add this command HttpContext.Current.Response.Write on update panel, and that because can not know how to handle it, because the update panel is return a struct that is used by the javascript to redraw some part of the page.
The solution is to add a literal control inside the UpdatePanel, in the place you wish to add the extra html code, and write that control the render as:
txtLiteralID.Text = sb.ToString();
How ever, here you have a diferent situation than the normal, you won to render and run a script.
The main problem is how to trigger the script to run. The only way is to use the UpdatePanel handler that is this standard code:
<script type="text/javascript">
// if you use jQuery, you can load them when dom is read.
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel run the code.
UnloadMsgBox();
}
</script>
Now on the EndRequest you need to call your script, where it may all read exist in your code as:
function UnloadMsgBox()
{
// render your code of the javascript.
$('body').append(\"<div id='M'><span id='text'></span><br/><div id='BB' onclick='return BB();'><a href='' onclick='return BB();'></a></div></div>\");
function BB() { $('#M').remove(); $('#E').remove(); return false; }"
function dM(){ var browser = navigator.appName; if (browser == 'Netscape') { $('#M').css({ 'top': '5%' }, 500); } }"
}
and not need to render it on UpdatePanel.
To summarize:
On the update panel you can not use the Response.Write to render something but a literal control, that renders inside him.
On the update panel you can not render javascript code and expect to run, to run a javascript code you need to use the EndRequest handler that comes with the UpdatePanel.
MS Ajax calls perform full page rendering, calculate the diff from the original, send the diff to the client, and magically merge the diff in the browser.
If you just send javascript as response, it's something the framework does not expect and it throws the message.
See a previous answer on how to invoke javascript from an UpdatePanel.
Trying to pass value (abc) from code-behind to JavaScript but the page fails and doesn't load. Is there something wrong with the syntax? I've noticed that normally the <%...%> is highlighted yellow but this is not the case in my code.
<script src="../Scripts/jqModal.min.js" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() { });
$("a").click(function() {
if (this.id == "optionalFeatures_Online") {
var abc = "<%=Variable_codebehind %>";
}
});
</script>
Code Behind On_Load event:
protected override void OnLoad(EventArgs e)
{
Variable_codebehind = "hello world";
}
Error from logfile:
Web.HttpUnhandledException' was thrown. ---> System.Web.HttpException: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
first bind the value to a hidden control
then get the value from the hidden control
<script src="../Scripts/jqModal.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
if (this.id == "optionalFeatures_Online") {
var abc = <%=Variable_codebehind %>;
}
});
});
</script>
Code Behind On_Load event:
protected override void OnLoad(EventArgs e)
{
Variable_codebehind = HttpUtility.JavaScriptStringEncode("hello world", true);
}
You can use Page.RegisterStartupScript and pass some variables from Code-Behind. Place the script in a .js file and call it on OnLoad method from the code-behind:
OnLoad CodeBehind:
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", String.Format("MyScript({0});", codeBehindVar));
MyScript.js
function MyScript(myVar)
{
var self = this;
$("a").click(function() {
if (this.id == "optionalFeatures_Online") {
var abc = self.myVar;
}
}