Calling jQuery function from C# - c#

I have the function below which needs to be called from C#
$('.image-cropper').each(linkUp);
Can anyone explain how it could be done. I tried using the below code
String csname1 = "PopupScript";
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type=\"text/javascript\"> $('.image-cropper').each(linkUp); </");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname1, cstext2.ToString(), false);
but it did not work.

You should really be calling your code inside the jQuery ready function ie:
$(function() {
$('.image-cropper').each(linkUp);
});
The likely reason your code wasn't working was that the image-cropper elements weren't in the DOM when your code was run.

Related

Unable to call jQuery function from class file in C# project

I am working on C# project. On masterpage,I have a jquery function named "myfunction" .
While trying to call this function from a class file I am getting error on browser console "Uncaught ReferenceError: myfunctionis not defined".
function myfunction(){
// code
}
string script = "";
script = "<SCRIPT language='javascript'>myfunction(); </SCRIPT>";
var obj = ((Object)(HttpContext.Current.Handler));
Type scriptType = obj.GetType();
ClientScriptManager cs = ((Page)(HttpContext.Current.Handler)).ClientScript;
cs.RegisterStartupScript(scriptType, "alert", script.ToString());
While working on any C# website, I can call this function from class file as well but here getting error. Even if I use update panel then function executes but without update panel its not executing.
Change the type on the script declaration:
script = "<SCRIPT language='text/javascript'>myfunction(); </SCRIPT>";
Remove the redundant ToString() call:
cs.RegisterStartupScript(scriptType, "alert", script);
And make sure myfunction() is output on the HTML before your script is inserted.

C# Script Block Register

Any one can help me because i'm Trying to register a script first and bind a function called "DoClick()" into button using C# but some error is occurred during runtime. please see my code below. so that when button was click they call the function "DoClick(). Thanks Guys
public void regiterAdsScript(int loc)
{
string adsLink = ads_link(loc);
// Define the name and type of the client script on the page.
String csName = "ButtonClickScript";
Type csType = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\"> \n");
csText.Append("function DoClick() { <script type='text/javascript' src='//abcd.site?id=123'></script> } \n");
csText.Append("</script>");
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
Button1.Attributes.Add("onClick", "return DoClick()");
}
}
Your script registration code should be like this
Button1.Attributes.Add("onClick", "javascript:DoClick();");
Also, your script looks wrong. Whatever you want your script to do should be followed by function declaration. Like if you want to put an alert it should be like this
csText.Append("function DoClick() { alert('MK'); } \n");
You also need to call the function regiterAdsScript() before the Button1_Click is called. I've called it in the Page_load itself. Below is sample program for you:
protected void Page_Load(object sender, EventArgs e)
{
regiterAdsScript();
}
protected void Button1_Click(object sender, EventArgs e)
{
//functionality to be implemented
}
public void regiterAdsScript()
{
string adsLink = ads_link(loc);
// Define the name and type of the client script on the page.
String csName = "ButtonClickScript";
Type csType = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\"> \n");
csText.Append("function DoClick() { alert('MK'); } \n");
csText.Append("</script>");
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
Button1.Attributes.Add("onClick", "javascript:DoClick();");
}
}

how to cal javascript method in server side button control?

function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
my button event is not fired...i want to shows the get directions using two dropdown list controls using server side controls but my button event is not fired ...wht i do?
<asp:Button ID="btnsubmit" runat="server" OnClientClick="return calcRoute();" Text="Submit" />
how to cal javascript method into serverside...please tell me..
Why have you got a server side button in the first place?
The button doesn't call a submit event, nor does it post back to the server. So why not simply use a normal html button?
Even your Javascript function doesn't return a true or a false so using return calcRoute() will always return a false event.
In any case, try using the normal onClick event rather than OnClientClick.
edit
Seems to me a lot of what you are doing here could be solved using jQuery in a much better way than you are trying to do here.
Syntax :
public void RegisterClientScriptBlock(
Type type,
string key,
string script,
bool addScriptTags
)
Parameters
type
Type: System.Type
The type of the client script to register.
key
Type: System.String
The key of the client script to register.
script
Type: System.String
The client script literal to register.
addScriptTags
Type: System.Boolean
A Boolean value indicating whether to add script tags.
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
String csname2 = "ButtonClickScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
{
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
cstext2.Append("Form1.Message.value='Text from client script.'} </");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
}
}
I am not add "return" false condition...My Button is getting a PostBack right now, that could be a problem. So add
Return false;
condition..
Then it will be working fine...thanks for the response..

ASP.net alert box using RegisterStartupScript, produce javascript code but with error

I have this C# code in my class:
private static void error_message(Sybase.Data.AseClient.AseException salah)
{
Page executingPage = HttpContext.Current.Handler as Page;
Type cstype = HttpContext.Current.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = executingPage.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, "PopupScript"))
{
String cstext = "alert('" + salah.Message + "');";
cs.RegisterStartupScript(cstype, "PopupScript", cstext, true);
}
}
which produce this code
<script type="text/javascript">
//<![CDATA[
alert('ua_services not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).
');//]]>
</script>
But the alert box doesn't show up, and Chrome logs an error "Uncaught SyntaxError: Unexpected token ILLEGAL "
What's wrong with my code?
Your salah.Message contains a CRLF. Trim it or escape it.
Or wrap RegisterStartupScript in a method that does it.

calling javascript from c#

I need to use the javascript functions to show and hide an element on my page, but calling it from within a C# method. Is this possible?
EDIT : I tried RegisterStartupScript (see below) but this did not hide the elements as I had hoped :
HidePopup("CompanyHQSetup", "$('#<%=DivDataProvider.ClientID %>').hide();$('#<%=modalOverlay.ClientID %>').hide();");
private void HidePopup(string Key, string jscript)
{
string str = "";
str += "<script language='javascript'>";
str += jscript;
str += "</script>";
RegisterStartupScript(Key, jscript);
}
EDIT : Got around this by using a hidden field boolean to determine whether or not to hide or show the elements
Yes, check out RegisterClientScriptBlock.
Here's a snippet taken from that link:
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client script on the page.
String csName = "ButtonClickScript";
Type csType = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\"> function DoClick() {");
csText.Append("Form1.Message.value='Text from client script.'} </");
csText.Append("script>");
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
}
One is server side, the other is client side. They can pass variables to each other (Javascript to ASP would be via forms/querystring/cookies and ASP to JS done via response.writing variables), but they can't directly interact.
you can use page.RegisterClientScript method to do that go on the following url
http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerclientscriptblock.aspx
and give it a try
Javascript is client side, c# is server side. You can't call javascript directly from C#. Take a look at Comet though, it will show you how you can push data from the HTTP server to the webpage.

Categories

Resources