Call javascript from server side on postback - c#

var r = {
init : function(){
r = Raphael("pie");
//r.g.txtattr.font = "12px 'Fontin Sans', Fontin-Sans, sans-serif";
r.g.text(320, -330, "Message Status").attr({ "font-size": 20 });
var pie = r.g.piechart(360, -180, 100, <%= Session["uStats"] %>, { legend: [<%= Session["vkeyColor"] %>], colors: [<%= Session["vPieColor"] %>] });
pie.hover(function () {
this.sector.stop();
this.sector.scale(1.1, 1.1, this.cx, this.cy);
if (this.label) {
this.label[0].stop();
this.label[0].scale(1.5);
this.label[1].attr({ "font-weight": 800 });
}
}, function () {
this.sector.animate({ scale: [1, 1, this.cx, this.cy] }, 500, "bounce");
if (this.label) {
this.label[0].animate({ scale: 1 }, 500, "bounce");
this.label[1].attr({ "font-weight": 400 });
}
});
var r = Raphael("pie"),
data2 = [<%= Session["vProgressPercentage"] %>];
axisx = ["10%", "20%"];
r.g.txtattr.font = "12px 'Fontin Sans', Fontin-Sans, sans-serif";
r.g.barchart(80, 25, 100, 320, data2, { stacked: true, colors: [<%= Session["vProgressColor"] %>,'#fff'] });
axis2 = r.g.axis(94, 325, 280, 0, 100, 10, 1);
}
}
window.onload = function () {
r.init();
};
The Javascript is executed when the page loads, I do partial postback using a update panel, the javascript is not executed during post back how to call it from server side.
<asp:ScriptManager ID="smCharts" runat="server" />
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
r.init();
}
function EndRequestHandler(sender, args) {
r.init();
}
</script>
<asp:UpdatePanel runat="server" ID="Holder" OnLoad="messsagePercentStats" UpdateMode="Conditional">
<ContentTemplate>
<div id="pie" onclick="__doPostBack('Holder', '');" style="top: -125px; left: -20px; width: 610px; position: relative;
height: 389px;">
</div>
This is what I am trying and the graph is not changed. it remains constant as in page load
protected void Timer_Tick(object sender, EventArgs args)
{
String MsgID = HttpContext.Current.Request.QueryString["MsgID"];
int msgID = Convert.ToInt32(MsgID);
BindGridViewUsers(msgID);
ClientScript.RegisterStartupScript(this.GetType(), "loadpie", "r.init();");
Holder.Update();
}

Use ScriptManager.RegisterStartupScript to call a javascript function from an update panel; something like this:
ScriptManager.RegisterStartupScript(this,this.GetType(),"key","javscriptfunction();" , false);

You could put this script inside a function:
function foo() {
...
}
which will be executed upon DOM load:
window.onload = function () {
foo();
};
and upon server side postback from an UpdatePanel:
ScriptManager.RegisterStartupScript(this, this.GetType(), "foo", "foo();", true);

window.onload does not work after the page has already loaded. Use
$(function(){ r.init();})
instead.

You could also do
Response.Write("<script language='javascript'>alert('I'm an alert');</script>");
Just put your code in instead of the alert. You might be able to call the function from there, but I haven't tested that.

Related

geckofx , c# add event listener

i'm using geckofx 29. how i can call c# function on javascript event ?
i search and find this solution, but its not working:
public void AddEventListener_JScriptFiresEvent_ListenerIsCalledWithMessage()
{
string payload = null;
browser.AddMessageEventListener("callMe", ((string p) => payload = p));
browser.LoadHtml(
#"<!DOCTYPE html>
<html><head>
<script type='text/javascript'>
window.onload= function() {
event = document.createEvent('MessageEvent');
var origin = window.location.protocol + '//' + window.location.host;
event.initMessageEvent ('callMe', true, true, 'some data', origin, 1234, window, null);
document.dispatchEvent (event);
}
</script>
</head><body></body></html>");
browser.NavigateFinishedNotifier.BlockUntilNavigationFinished();
Assert.AreEqual("some data", payload);
}
event.initMessageEvent can not execute ...
please help me
The message event interface has been updated. The initMessageEvent method no longer exists. Look here at bottom of the thread. According to that body of your onload function should be:
var event = new MessageEvent('callMe', { 'view': window, 'bubbles': false, 'cancelable': false, 'data': 'some data' });
document.dispatchEvent(event);
Hope this helps.

execute javascript from codebehind in asp.net

I need to fire this script from code behind only on certain dates specified in the database
I need to show an image as a fancybox based on the date specified in CMS system.
I will write my logic to show image or not in the Default.aspx and then somehow pass this piece of code from default.cs to MarterPage Javascript $(window).load(function () Code Block
<Script>
$(window).load(function () {
I want this code to fire at a particular location of master page. I am not sure suppose here.
///HERE???
});
</Script>
I want to pass below script as a value so that it js execute ///HERE??? part of code
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "$('a.fancybox-messageboard').fancybox({ width: 600, height: 440,closeClick: true, hideOnOverlayClick: true, href: 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg' }).trigger('click');", true);
I am bit lost with this ...
I simple want to do my logic check in Default.aspc file and show image as a fancy box only in default.aspx page. But my ' $(window).load(function () { });code block is in MasterPage file if i write another ' $(window).load(function () { }); in default.aspx file then fancy box is not showing properly.
How can i achieve this without any issue
UPDATE:
I managed to pull it off.. this is based on the solution posted by Irina Bogomaz.
So far this is working I can add full logic to code-behind later on.
$(window).load(function () {
if (window.showMessage) {
// alert(imgPath);
//logic to create fancybox
$("a.fancybox-messageboard").fancybox({
width: 600,
height: 440,
closeClick: true,
hideOnOverlayClick: true,
href: imgPath
}).trigger('click');
}
});
CODE BEHIND
protected override void OnPreRender(EventArgs e)
{
string imgMB = "'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg'";
string sScript = "var showMessage = true; var imgPath=" + imgMB;
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", sScript, true);
}
Try this:
string myscript = "$('a.fancybox-messageboard').fancybox({ width: 600, height: 440,closeClick: true, hideOnOverlayClick: true, href: 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg' }).trigger('click');"
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "<script>" + myscript + "</script>", false);
You can achieve this in the following way:
Master page:
<script type="text/javascript">
$(window).load(function () {
if (window.isFancybox) {
//logic to create fancybox
}
});
</script>
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
var fanceBoxDate = new DateTime(2013, 11, 20); //get date from CMS system
if (DateTime.Today == fanceBoxDate)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "fancyBox", "var isFancybox = true", true);
}
}
may be u will use this way
first make aspx page to get service and use web method (_service.aspx)
public partial class _service : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string binddata(yourObject yourDatabaseObject)//tbl_BI_mant[]
{
//connect to Database
//and add your Date filter
return Data.getpictureWithDateFilter(yourDatabaseObject.datefilter)
}
}
then in your default.aspx page call that service with jquery ajax
$(function () {
$.ajax({
url: '../_service.aspx/binddata',
type: 'POST',
data: " {'yourDatabaseObject':" + JSON.stringify(Parameters) + "}",
datatype: 'html',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('a.fancybox-messageboard').fancybox({ width: 600, height: 440,closeClick: true, hideOnOverlayClick: true, href: 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg' }).trigger('click');;
},
error: function (request, status, err) {
// alert(status);
//alert(err);
}
});
});

how to call jquery function call in asp.net c#?

I want to show division for 5 seconds while i do every postback in c#.I am using below function to do that but it doesn't work.
I used this code on page load in c#.
Page.ClientScript.RegisterStartupScript(Page.GetType(), "PostbackClick", "setTimeout(function() { $('#correct').fadeOut(1500); }, 5000)", true);
in aspx page
<script type='text/javascript' src='Scripts/scripts/jquery.min.js'></script>
<script type="text/javascript">
$(document).ready(function () {
$('#correct').hide();
});
</script>
<img alt="" id="correct" src="Que-img/correct.png" />
use
RegisterClientScriptBlock(Page.GetType(), "PostbackClick", "$(document).ready(function(){
setTimeout(function() { $('#correct').fadeIn(1500); }, 5000)});", true)
Because you have to wait for JQuery.ready before using jquery selectors. RegisterStartupScript actually happens before jquery ready.
in my answer your setTimer will executed on jquery ready
You already hiding the image in document.ready function
<script>
$(document).ready(function () {
//$('#correct').hide(); // remove this line or comment
// because fadeOut will work on visible elements
function hideImage() {
setTimeout(function() { $('#correct').fadeOut(1500); }, 5000);
};
});
</script>
In C#
Page.ClientScript.RegisterStartupScript(Page.GetType(),"PostbackClick", "script",
"hideImage();" true);
How to Call Jquery from C# will help you
I guess i got your issue ...Modify your code as below
$(document).ready(function () {
$('#correct').hide();
$('#btnId').click(function(){
$('#correct').show();
setTimeout(function() { $('#correct').fadeOut(1500); }, 5000);
});
});
and remove
Page.ClientScript.RegisterStartupScript(Page.GetType(), "PostbackClick", "setTimeout(function() { $('#correct').fadeOut(1500); }, 5000)", true);
Here is the demo

Close PopupJqueryDialogue with Iframe

I am Popup External url Page inside my current page using jQueryDialogue and Iframe
var iframe = $('<iframe frameborder="0" id="FrameCust" marginwidth="0" marginheight="0" allowfullscreen></iframe>');
var dialog = $("<div id='tempstep'></div>").append(iframe).appendTo("body").dialog({
autoOpen: false,
modal: true,
resizable: false,
width: "auto",
height: "auto",
close: function () {
iframe.attr("src", "");
}
});
$("input[id$='btnAddCust']").on("click", function AddCust(e) {
e.preventDefault();
var src = "../MasterPages/CustomerMaster.aspx?lpopup=True";
var title = "Customer Master";
var width = "980";
var height = "530";
iframe.attr({
width: +width,
height: +height,
src: src
});
dialog.dialog("option", "title", title).dialog("open");
});
In my customer master Codebehind File Checking Query string to Identifiey the page from Popup or Itself (lpopup='True')
I want to Close the PopupDialogue after click Save button inside the PopupDialogue (In the External Url)
how can i do that ?
You can pass query string in parent page from code behind of popup page using code below. This will also close the popup.
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "jain", "<script type='text/javascript' language='javascript'>parent.location.replace('../test.aspx?Q=123456');</script>");

Can java script add the contents below to a table aswell

Can java script add the contents below to a asp table aswell at the same time (with html tags)
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
$('#test1').append('<div id="test">' + x + '</div>');
return false;
});
});
</script>
<textarea style="border: 0" cols="77" rows="2">Write Something....</textarea>
<button>Post Message</button>
<div id="test1"></div>
</asp:Content>
something like:
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
$('#test1').append('<div id="test">' + x + '</div>');
//$save append aswell to Table1
return false;
});
});
</script>
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
var newdiv = $("<div></div>").html(x).attr('id','test');
$('#test1').append(newdiv);
$('#Table1').append(newdiv);
//$save append aswell to Table1
return false;
});
});
</script>
It seems like you are using jquery here.
Have you got your jquery framework loaded & tried your code to see if it works??
It is running fine on jsfiddle.net here
Updates
If your Table1 is on the same page.
All you need to do is to get hold of the DOM element.
if you have a table
<table id="Table1">
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
You can add after your code
$('#test1').append('<div id="test">' + x + '</div>');
this code
$('#Table1 tr:last').after('<tr><td>'+ x +'<td></tr>');
Hope you find this helpful

Categories