I want to call a c# function from JavaScript. I tried the solution specified in Call ASP.NET function from JavaScript? but the RaisePostBackEvent is not getting called.
My JavaScript is:
<script>
function link_load() {
var pageId = '<%= Page.ClientID %>';
__doPostBack(pageId, argumentString);
document.getElementById("sidebar1").innerHTML = "working";
}
</script>
My C# code is:
public void RaisePostBackEvent(string eventArgument)
{
sidebar1.InnerHtml = "working inside";
}
The JavaScript code is executed, which I verified.
[webmethod]
public void RaisePostBackEvent(string eventArgument)
{
sidebar1.InnerHtml = "working inside";
}
in javascriptenter code here
<script type="javascript">
$.ajax({
url:'pagename.aspx/RaisePostBackEvent'`enter code here`
enter code here
});
</script>
Related
I have a jQuery function:
<script src="Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
alert("1");
function hideInfo() {
alert("2");
$("#h3memberInfo").fadeOut("slow");
};
});
</script>
I am trying to call above function from c# as below.
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "hideInfo();", true);
On page load I get alert("1") but alert("2") is never triggered.
What wrong am I doing?
As your function hideInfo() is wrapped inside the $(document).ready block, its not available in the global scope as you try from the code behind.
You can modify your code as below,
<script src="Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function hideInfo() {
$(document).ready(function () {
alert("1");
$("#h3memberInfo").fadeOut("slow");
});
}
</script>
How to i calling jQuery function from code behind after button click...
<script>
$(document).ready(function () {
$(".chkOther").change(function () {
//console.log($(this).find("input[type=checkbox]").is(":checked"));
if (!$(this).find("input[type=checkbox]").is(":checked")) {
$(this).closest(".frome_group").find(".cleartxt").val("");
//$(this).closest(".frome_group").find(".cleartxt").attr('readonly',true);
}
else {
//$(this).closest(".frome_group").find(".cleartxt").removeAttr('readonly');
$(this).closest(".frome_group").find(".cleartxt").focus();
}
});
function successMessage() {
$("#successModal").modal('show');
}
function errorMessage() {
$("#errorModal").modal('show');
}
});
</script>
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "successMessage", "successMessage();", true);
The Problem with your question
You are asking, how to call a javascript action after button click. But additionally, you want to call it from code behind? Why do you not call it after clicking your button?
Please be sure to understand the HTTP client-server architecture before asking such questions.
Maybe you mean this?
Since you didn't specify the result you are aiming for, I have to assume that you want to call successMessage() or errorMessage() after finishing a Server request. You would do something like this using AJAX:
$.ajax({
url: "/API/Controller/Method",
success: function () {
successMessage();
},
error: function () {
errorMessage();
}
});
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
I'm developing a asp.net web application and I have this script in source code:
<script language="javascript" type="text/javascript">
function showWindow(URL, controlID, targetControlID,id)
{
noweOkno = window.open( URL + '?controlID='+controlID+'&targetControlID=' +
targetControlID+'&id='+ id, '_blank',
'menubar=no, toolbar=no, location=no, scrollbars=no, resizable=no, ' +
'status=no, width=760, height=600, left=30, top=30')
noweOkno.focus();
}
</script>
I can call it with this code:
Button4.Attributes["onClick"] = string.Format("showWindow( 'Child.aspx','{0}', '{1}','{2}');", tbVer.ClientID, Hidden1.ClientID, id_act);
my question is, how to call the javascript in some C# method like:
protected void someMethod()
{
-I want to call showWindow('Child.aspx','{0}', '{1}','{2}');", tbVer.ClientID, Hidden1.ClientID, id_act);
}
thanks
You can register script block to run on page like :
ClientScript.RegisterStartupScript(GetType(),"hwa","function_name;",true);
you can use clientscriptmanager
ClientScriptManager.RegisterStartupScript(this.GetType(), "AKey", "MyFunction();", true);
http://msdn.microsoft.com/en-us/library/asz8zsxy.aspx
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.