execute javascript from codebehind in asp.net - c#

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);
}
});
});

Related

Ajax respond is not reflected into pop-up view

I have created a button to pass some parameters to a controller and get the response in a responsive pop-up.
But somehow when I click the button, nothing happens. No error in Dev.Option (F12), and I already make sure the parameter goes into my controller.
My reference : http://aspsnippets.com/Articles/Open-Show-jQuery-Dialog-Modal-Popup-after-AJAX-Call-Success.aspx
I'm using MVC C# on Visual Studio 2010. Below is my code:
My home page, all pre-requisite Jquery are already automatically reloaded inside global.asax.
HomePage.cshtml
var externalID = "123";
var susbcrNo = "456";
<a href="#COV" onclick="javascript:CustomerOneView.displayPopUpWindow(#externalID, #susbcrNo);" >DETAILS</a>
<div id="dialog" style="display: none"/>
#section Scripts{
<script type="text/javascript" src="#Url.Content("~/Scripts/CustomerOneView.js")" ></script>
<script type="text/javascript">
$("#dialog").dialog({
autoOpen: false,
modal: true,
title: "Details",
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
Inside CustomerOneView.js :
var CustomerOneView = (function () {
return {
init: function () {
},
displayPopUpWindow: function (externalID, susbcrNo) {
var postData = {
externalID: externalID,
susbcrNo: susbcrNo
};
$.ajax({
type: "POST",
url: "/Home/OneViewDetails",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
$("#dialog").html(r);
$("#dialog").dialog("open");
}
});
}
};
})();
$(document).ready(function () {
CustomerOneView.init();
});
My controller :
[HttpPost]
public JsonResult OneViewDetails(string externalID, string susbcrNo)
{
Models deviceDetails = new Models();
deviceDetails.Code = externalID;
deviceDetails.Message = susbcrNo;
// call log here make sure the values.
Logger.Debug("COV called here " + externalID + " - " + susbcrNo);
// old return
// return Json(deviceDetails, JsonRequestBehavior.DenyGet);
return Json(deviceDetails);
}
My Controller is already tied into a view that supposed to be a pop-up view. Let's call it PopUp.cshtml
How can I fix this issue?
I need to clarify something about C# on the server side; if you return a value on a function/method, it will return the value to the code that called said function/method as opposed to intelligently guessing that you want to print the value back to the client so the browser may then manipulate the results?
If that is the case, you need to echo or print the return value from the function/method or from where the function/method is called.

Fancybox doesn't work after a success of an ajax call

Why is not working fancybox after check validation in c#?
fancybox is call after use PageMethods.ValidacionIsAdmin(onSuccessValidacionIsAdmin); if it is valid the return of database executed in:
[WebMethod]
public static DeleteAccountResult ValidacionIsAdmin()
{
DeleteAccountResult res = new DeleteAccountResult();
... // Query to database with ok results
res.ok = true;
return res;
}
The ajax call in client to validate it is:
jQuery(".delete a").click(function () {
function onSuccessValidacionIsAdmin(data) {
if (data.ok == true) {
jQuery("#<%= divError.ClientID %>").hide();
jQuery(".delete a").fancybox({
content: jQuery('#eliminar-cuenta').html(),
modal: false,
showCloseButton: false,
onComplete: function () {
jQuery("input[type=checkbox]").uniform()
jQuery('#privacidad').fancybox({
enableEscapeButton: false,
hideOnOverlayClick: false,
showCloseButton: true,
onComplete: function () {
jQuery('#fancybox-close').off().on('click', function (e) {
e.preventDefault();
jQuery(".delete a").click();
});
}
});
}
});
}
else {
jQuery("#<%= divError.ClientID %>").show();
jQuery("#lblError")[0].innerHTML = data.strError;
}
}
PageMethods.ValidacionIsAdmin(onSuccessValidacionIsAdmin);
});
The Behaviour is look like after to push the link which open fancybox don't open it, looks like it "refresh" the web and I push the same link and then it is working...
I readed fancy doesn't work after an ajax call (in my case the c# validation)
My question is: why it happens?
After some hours of investigation, I got the solution. It is curious, in all propierties ineas to write content: ... I replaced as: 'content': ...
I added the property 'type':'html'
After do that the fancybox was working.
jQuery(".delete a").fancybox({
'content': jQuery('#eliminar-cuenta').html(),
'type': 'html',
'modal': false,
'showCloseButton': false,
'onComplete': function () {
jQuery("input[type=checkbox]").uniform()
jQuery('#privacidad').fancybox({
enableEscapeButton: false,
hideOnOverlayClick: false,
showCloseButton: true,
onComplete: function () {
jQuery('#fancybox-close').off().on('click', function (e) {
e.preventDefault();
jQuery(".delete a").click();
});
}
});
}
});

calling a serverside method in a javascript function?

Here i am calling a javascript function on a button click and i need to call the server side method inside the javascript function after finishing its execution.
Javascript Function
function exportCharts(exportFormat) {
initiateExport = true;
for (var chartRef in FusionCharts.items) {
if (FusionCharts.items[chartRef].exportChart) {
document.getElementById("linkToExportedFile").innerHTML = "Exporting...";
FusionCharts.items[chartRef].exportChart({ "exportFormat": exportFormat });
}
else {
document.getElementById("linkToExportedFile").innerHTML = "Please wait till the chart completes rendering...";
}
}
}
Server side Method
protected void imgBTNExportPPT_Click(object sender, ImageClickEventArgs e)
{
try
{
PredictExportToPPT objOExporttoPPT = new PredictExportToPPT();
PredictionModel();
string reportNames = ObjCommon.GetBIReportNames("Prediction", "Report");
reportNames += ObjCommon.GetBIReportNames("Prediction", "Table");
objOExporttoPPT.ExportToPPTPredict(ObjPredictInputParameter, reportNames, ObjSharedEntities.PredictTableData);
string itemname = "PPTOutput.pptx";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "pptx";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + itemname + "");
HttpContext.Current.Response.BinaryWrite(System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(DataTemplate.PPTOutputTemplateFilePath)));
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
catch (Exception exceptionMessage)
{
throw (exceptionMessage);
}
finally
{
GC.Collect();
}
}
and i have tried like this
$(document).ready(function () {
$("#imgBTNExportPPT").click(function (e) {
e.imgBTNExportPPT_Click();
$.ajax({
type: "POST",
url: "PEventPerformance.aspx/updateContent",
data: "{}",
success: function (result) {
}
});
});
});
Any suggestion??
Your imgBTNExportPPT_Click looks like an click event of a button. You may try the following to raise the event from JavaScript
Place this javascript in aspx page
<script type="text/javascript">
function myfunc() {
<%= Page.ClientScript.GetPostBackEventReference(imgBTNExportPPT, String.Empty) %>;
}
</script>
Call this function against OnClientClick
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="myfunc();" />
This will fire the server side event:
protected void imgBTNExportPPT_Click(object sender, ImageClickEventArgs e)
{
}
You can use Ajaxpro for this purpose, If u want to generate a server side call without any event like button click.
In Your code behind file. Under the Page_Load section add
AjaxPro.Utility.RegisterTypeForAjax(typeof(YourCodebehindfilename));
In client side
call the server side method like
var content = YourCodeBehind.Yourmethod(optional parameters).value;
In content you can get your response as an object and can do further changes
I guess the best way to execute server side method is to use Web Services.
You have to write a Web Service that that contains your server side method.Then you can call it using AJAX.

Call javascript from server side on postback

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.

RegisterClientScriptBlock In userControl

This is my jquery and javascript code :
<script type="text/javascript">
$(document).ready(function () {
//setup new person dialog
$('#dialog').dialog({
modal: true,
modal: true,
// show: "clip",
// hide: "explode",
autoOpen: false,
title: "انتخاب فاکتور",
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
//setup edit person dialog
$('#editPerson').dialog({
autoOpen: false,
draggable: true,
title: "Edit Person",
open: function (type, data) {
$(this).parent().appendTo("form");
}
});
});
function showDialog(id) {
$('#' + id).dialog("open");
}
function closeDialog(id) {
$('#' + id).dialog("close");
}
The Code Is in UserControl .
i can show Dialog client Side :
and i can register code from server with this code :
Page.ClientScript.RegisterClientScriptBlock(GetType(String), "script", "$(function() {showDialog('dialog');});", True)
this code works in page but not in user control.
how can i fix it?
HTML Code :
'>
' runat="server" />
Not sure whether this is the issue or not. Since UserCOntrol is a naming container your element id might have changed. So you need to get the id using ClientID.
Change your code to something like this
$("#<%=yourbuttonid.ClientID%>").dialog("open");
Check the rendered HTML code of your page. Is the order of your script blocks correct? The setup block should be first there, and the showDialog call block should be rendered somewhere below it. Is it your case?

Categories