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);
Related
Hello i am failing to pass the value from dropdownlist in the parent aspx form to textbox in the child aspx form
Parent javascript
: The First script is to open the popup window
<script type="text/javascript">
var popup;
function NewCustOpn() {
popup = window.open("NewCustomer.aspx","Popup",toolbar=no,scrollbars=no,location=no,statusbar=no,menubar=no,resizable=0,width=520,height=350,left = 250,top = 50");
}
</script>
This is the second script on the parent page to get the value of the dropdownlist
<script type = "text/javascript">
function parentFunc()
{
return document.getElementById ("<%=DropDownList1.ClientID%>").value;
}
</script>
The child page javascript:
<script type = "text/javascript">
window.onload = function ()
{
if(window.opener != null && !window.opener.closed)
{
var val = window.opener.parentFunc();
var textbox = document.getElementById("<%=TextBox1.ClientID%>");
textbox.Value = val;
}
}
</script>
When the popup opens TextBox1 is empty.
Your problem is simple. Just replace the below line from your child page's js function
textbox.Value = val;
to
textbox.value = val; // lowercase "v"
or justdo a direct assignment like this
document.getElementById("<%=TextBox1.ClientID%>").value = val;
Or another possible solution would be to directly pass the required value from the parent page as a querystring value and you don't need the js function in the popup page. The querystring value you can access it in child pages's page load event and assign it directly to the textbox.
Your Parent js
function NewCustOpn() {
var ddlvalue = document.getElementById("<%=DropDownList1.ClientID%>").value;
var popup = window.open("Popup.aspx?dropdownval=" + ddlvalue, "Popup", "toolbar=no,scrollbars=no,location=no,statusbar=no,menubar=no,resizable=0,width=520,height=350,left = 250,top = 50");
}
And from you child page's code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["dropdownval"])) {
TextBox1.Text = Request.QueryString["dropdownval"];
}
}
I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}
How to open a radwindow on the click event of a Imagebutton within a user control?
Moreover i have used the same code in aspx page and it works fine.
car.ascx
code behind car.ascx.cs
protected void btnCarLogo_Click(object sender, ImageClickEventArgs e)
{
carurl="https://www.google.co.in/"
ScriptManager.RegisterStartupScript(this, this.GetType(), "popCarWindow", "window.radopen('" + carurl + "', 'CarDetails');", true);
}
It has VisibleOnPageLoad property. If you set it to true, window will be visible after postback.
Examples:
Show window
myRadWindow.VisibleOnPageLoad = true;
Hide window
myRadWindow.VisibleOnPageLoad = false;
Take a look here: http://www.telerik.com/community/forums/aspnet-ajax/window/opening-radwindow-from-the-server.aspx and see that the parameters are Page and not this (i.e. UserCOntrol).
Here is on working with JS functio nnames in user controls: http://www.telerik.com/support/kb/aspnet-ajax/general/using-dynamic-unique-names-for-javascript-functions.aspx
And, if you are going to have more than one manager on the page: http://www.telerik.com/help/aspnet-ajax/radwindow-troubleshooting-wrong-window-opened.html.
That way probably you get errors stating that the window is null
Try it like this:
Code behind:
string script = "<script language='javascript' type='text/javascript'>Sys.Application.add_load(ShowWindow);</script>";
ClientScript.RegisterStartupScript(this.GetType(), "showWindow", script);
Then on your aspx:
<script type="text/javascript">
function ShowWindow()
{
var oWnd = window.radopen('https://www.google.co.in/', 'window1');
}
</script>
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
I write script like this in my .cs file :
StringBuilder script = new StringBuilder();
script.Append("<script type=\"text/javascript\"> function submitform(){");
script.Append(" document.forms['" + ((HtmlGenericControl)frm).Attributes["id"] + "'].submit();} </");
script.Append("script>");
How can i call this function in the OnClientClick of my link button ?
LinkButton hl_process = new LinkButton();
hl_process.OnClientClick = ""
Edit1:
protected Control CreateCommForm()
{
HtmlGenericControl frm = new HtmlGenericControl("form");
frm.Attributes.Add("id", "sal");
frm.Attributes.Add("method", "post");
frm.Attributes.Add("action", "https://------");
/////////////////////////////////////////
HtmlGenericControl hdn_sal_a = new HtmlGenericControl("input");
hdn_sal_a.Attributes.Add("id", "hdn_sal_a");
hdn_sal_a.Attributes.Add("name", "hdn_sal_a");
hdn_sal_a.Attributes.Add("type", "hidden");
hdn_sal_a.Attributes.Add("value", Session["emp_num"].ToString());
/////////////////////////////////////////
HtmlGenericControl hdn_sal_b = new HtmlGenericControl("input");
hdn_sal_b.Attributes.Add("id", "hdn_sal_b");
hdn_sal_b.Attributes.Add("name", "hdn_sal_b");
hdn_sal_b.Attributes.Add("type", "hidden");
hdn_sal_b.Attributes.Add("value", Session["user_name"].ToString());
frm.Controls.Add(hdn_sal_a);
frm.Controls.Add(hdn_sal_b);
column1.Controls.Add(frm);
return frm;
}
separate the concerns The Visual part your application shouldn't be affected if you move your app to java or ruby. that's what separate of concerns is.
write the client script in the client, not in the cs file:
$('#<%= hl_process.ClientID %>').click(function(){
...
$('#formId').submit();
// if the button inside the form:
this.form.submit(); // HTML5
// Or:
$(this).closest('form').submit();
// if the button not inside the form :
var class = $(this).attr('class');
$('form.' + class).submit();
});
Use jquery to bind to the click event instead of doing this on the server side:
Submit Me
then in javascript something like:
<script type="text/javascript">
$('.blah').click(function() {
document.forms[0].submit();
});
</script>
Edit:
While you can generate UI elements with codebehind it's not quite the asp.net way. Use repeaters if you must repeat the generation of controls. Actually, creating multiple forms is not the asp.net way either, as it assumes only one form running at the server context and everything else binds to an event on submission. Anyways, it seems you're still learning asp.net and probably coming form PHP or something similar.
To accommodate your request, I'd advice to stay away from from generating JS on the server side. Give different class names to your forms and use the same method above. You don't need a LinkButton to submit the form, a simple anchor <a> fits the bill.
You can use the ClientID property (if you don't use classes), but you must first attach the parent control to the page for the algorithm to kick in.
So, your code would be something like:
protected Control CreateCommForm()
{
...
column1.Controls.Add(frm);
HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes["onclick"] = "$('#" + frm.ClientID + "').submit();";
a.InnerText = "Submit me";
frm.Controls.Add(a);
return frm;
}
The alternative way (better separation of concerns)
protected Control CreateCommForm()
{
...
column1.Controls.Add(frm);
HtmlGenericControl a = new HtmlGenericControl("a");
a.Attributes["class"] = "submitter";
a.InnerText = "Submit me";
frm.Controls.Add(a);
return frm;
}
And in javascript we find the parent form and submit it (this can be in a static js file):
<script type="text/javascript">
$('.submitter').click(function(
$(this).parents('form').submit();
));
</script>