Call JavaScript function from C#? - c#

JQuery
$(document).ready(function () {
function btnekle(){
$('#icerik-right').animate({
scrollTop: $('#icerik-right').offset().top + $('#icerik-right')[0].scrollHeight
}, 2000);
return false;
}
});
C#
ClientScript.RegisterStartupScript(GetType(), "script", "btnekle();", true);
Where can I make mistakes ??

There is no need for ready function you can directly write like this
function btnekle(){
alert('Called');
$('#icerik-right').animate({
scrollTop: $('#icerik-right').offset().top + $('#icerik-right')[0].scrollHeight
}, 2000);
return false;
}
I suggest you try to debug by putting alert for debugging (to check function called or not) or try to debug things with help of developer tool bar .

Related

MVC ActionLink calling multiple JQuery functions

I'm trying to call a confirm, then an alert function from an MVC action link and I'm stuck. The code is as follows:
My view has the following actionlink:
#Html.ActionLink("JQuery Testing", "BuildProject", Model, new { onclick = " return ConfirmProjectSubmit()" })
which calls the controller to save a project to the database. I'm trying to throw a confirm statement onClick. Once that action is performed, the following action is called:
return RedirectToAction("ProjectDetails", "Project", new RouteValueDictionary(new { id = currentProject.Id, msg = message }));
to alert the user that the project was actually created.
and then at the bottom of my view:
#section scripts {
<script type="text/javascript">
function ConfirmWorkflowSubmit() {
$.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function () {
},
cancel: function () {
}
}
});
return false;
};
</script>
#if (ViewBag.message != null)
{
<script type="text/javascript">
$(document).ready(function () {
$.alert({
title: 'Workflow successfully created',
content: '#ViewBag.message',
type: 'green',
});
});
</script>
}
}
both of the actions are firing, but incorrectly. I'm newer to MVC and moreso to Jquery. Basically I need to figure out how to not have it submit if the user doesn't confirm, and then make sure the message only pops on the way back. I think I just need help ordering what I have properly.
Thanks in advance.
EDIT. Okay, so I see part of the problem. It's not the $confirm function that's actually submitting the form, it's the button action clicked once the dialog is open. I'm really stuck here, and this has to be easier than I'm making it. Help!
I'm not saying you can't do it the way you have, but this is normally how I set up my bindings:
$(document).ready(function ()
{
// add the e here -- it is the event which initiated the binding
$(".buildButton").on("click", function (e)
{
if (ConfirmProjectSubmit())
{
alert('confirm');
}
else
{
// e.preventDefault() cancels the click action
e.preventDefault();
alert('cancel');
}
});
});
function ConfirmProjectSubmit()
{
// some confirm logic
// return true for confirmed, false for cancelled
return false;
}
Remove the onclick in your action. There is no need to have a jQuery binding and an onClick.
This is sort of an outline, you can add your logic in various places to finish it out.

Function call from code behind

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

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

call JavaScript function from code behind

I have this JavaScript code in an ASPX page
<script>
function show_modal(statut)
{
if (statut == true)
{
$(function ()
{
$('#modal_success').modal('show')
})
}
else
{
$(function ()
{
$('#modal_fail').modal('show')
})
}
}
</script>
That shows an modalpopup which I like to launch from my code behind.
I tried this, but it didn't work:
if (resultat)
{
ClientScript.RegisterStartupScript(this.GetType(), "", "show_modal(true);");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "", "show_modal(false);");
}
but I can't figure out why!
This call requires you to wrap the call in a <script> tag (or use the other overload which allows you to specify if script tags are added)
ClientScript.RegisterStartupScript(this.GetType(), "",
"<script>show_modal(true);</script>");
or
ClientScript.RegisterStartupScript(this.GetType(), "",
"show_modal(true);", true);
Try:
ScriptManager.RegisterStartupScript(this.Page, typeof(Page), Guid.NewGuid().ToString(), script, true);
Try using ScriptManager.RegisterClientScriptBlock Method => it should work and for more check the Error console for tracing your issue.

Calling WebService from Ajax/Javascript

I am getting into a little jam here. I created a webservice using C#. When I Invoke the WebService it works fine. The Javascript seems to be hitting the webservice, breaking, and then follows through with the rest of the operation. I think this is a matter of me calling the WebService wrong. I've searched all over and have found tons of different examples, however, none of them seem to work.
If you go to http://success.darkslidedesign.com it triggers test.js which then calls my web service located here: http://www.darkslidedesign.com/services/ms_Alert.asmx
Here is the test.js code -
var xmlHttp;
setTimeout("sendMessage('rory#careercheatcode.com');", 2000);
function doUpdate()
{
if(xmlHttp.readyState===4){
alert("Worked");
}
else{
alert("Broke");
}
}
function sendMessage(strTo)
{
try{
// Opera 8.0+, Firefox, Safari
xmlHttp = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Ajax is not supported
return false;
}
}
}
xmlHttp.open("post", "http://www.darkslidedesign.com/services/ms_Alert.asmx", true);
var params = "op=Sending_Email&strEmailAddrFrom=rory#darkslidedesign.com&strEmailAddrTo=" + strTo;
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange=doUpdate;
xmlHttp.send(params);
return false;
}
You better start with jQuery $.ajax()
Here is one snippet that works for me to post comment from a textbox.
function Post() {
var ow = "username";
var cmt = $("#comment").val();
$.ajax(
{
type: "POST",
url: "/comment/Save",
dataType: "json",
data: "id=2332&author=" + ow + "&cmt=" + cmt,
success: function (result) {
if (result.status === "OK") {
alert('Comment posted');
}
else
alert("Post failed");
},
error: function (req, status, error) {
alert("Sorry! Post failed due to error");
}
});
}
Hope this will guide you.
Thanks
For web service calls from Javascript, I use two things:
jQuery, as pixelbobby mentioned. It is a walk in the park and makes everything super awesome-sauce!
I use the asp.net MVC framework. It is far too verbose for me to explain it here, but it is pretty easy to get it up and running. Basically, you create a controller class, create some methods, and return json-serialized values. You might also have to add some routes to your global.asax file.
I would definately recommend reading up on both of these things... They are both pretty awesome!

Categories