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();
}
});
Related
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.
I have MVC project. I need to do client side validation on run time. When click the form submit button I need to hit JavaScript Method first and then it is return true move to Controller method.
Just Assume following code type:
JavaScript OnClick Method:
$(function () {
$('#btnSave').on('click', function (event) {
$.ajax({
url: '/Service/Utility/ThresholdValidation',
type: $("#addNewOrderForm").attr('method'),
data: $("#addNewOrderForm").serialize(),
success: function (data) {
if (data != "") {
event.preventDefault();
alert(data);
return false;
}
else {
return true;
}
}
});
});
});
Controller Method:
[HttpPost]
[BaseAuthenticationFilter(UserTypeEnum.Admin, PermissionEnum.CanSendRemittance)]
public ActionResult Create(Invoice model)
{
// Method Goes here
}
Here I cant popup validation alert message. When I click the button it will hit the Controller method. I need to go first javascript method and then if true go to controller method
Please help this.
Try following code, you have to return false in click handler directly instead of ajax response event. because ajax is asynchronous it will execute the ajax and call out from event handler immediately before getting the response of ajax.
So check if data not exists then submit the form otherwise show validation message
$('#btnSave').on('click', function (event) {
$.ajax({
url: '/Service/Utility/ThresholdValidation',
type: $("#addNewOrderForm").attr('method'),
data: $("#addNewOrderForm").serialize(),
success: function (data) {
if (data != "") {
alert(data);
}
else {
$("form").submit();
}
}
});
event.preventDefault();
return false;
});
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 trying to implement jquery onclick confirmation dialog to my mvc3 delete actions.
Worth to mention is that I'm succ. render dialog itself, where I'm struggle is process action to /User/Delete action from js after the continue button is clicked. Here's the code:
onclick-delete.js
$(function () {
var deleteLinkObj;
// delete Link
$('.delete').click(function () {
deleteLinkObj = $(this); //for future use
$('#delete-dialog').dialog('open');
return false; // prevents the default behaviour
});
//definition of the delete dialog.
$('#delete-dialog').dialog({
autoOpen: false, width: 400, resizable: false, modal: true, //Dialog options
buttons: {
"Continue": function () {
$.post(deleteLinkObj[0].href, function (data) { //Post to action
// THIS IS WHERE I SHOULD SEND DATA TO MY DELETE ACTION (Users/Delete)
else {
alert("error");
}
});
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
});
So, what I'm doing wrong.
After clicking error is thrown, any ideas
Correct me if I wrong, but isn't this way simpler and more effective
#Html.ActionLink("Delete", "Delete",
new { id = item.Id },
new { onclick = "return confirm('Are you sure you wish to delete this article?');" })
As per the discussion in Mark Oreta's answer, here's what I would do:
If you set up the form like always, you can still get confirmation from the user without too much hassle. Take the following HTML/JS:
<form action="/User/Delete" method="post">
<!-- some fields here -->
<input id="btnSubmit" type="submit" value="Delete" />
</form>
This should properly submit the form to the backend. Interesting to note is that if you click the submit button, any click event set up in javascript/jQuery will be executed before submitting the form.
So you can do:
$("#btnSubmit").click(function(event) {
event.preventDefault(); // --> This stops the form submit from happening.
});
If all you need is a textbox in which the user confirms, there is no need to use anything other than the standard confirm() function. This messages the user and asks him to either agree or cancel. The function returns true/false according to the user's response.
So you can write the simplest of code:
$("#btnSubmit").click(function(event) {
var confirmationmessage = "Are you sure you want to delete this?";
if( ! confirm(confirmationmessage) ) {
// !confirm == the user did not confirm. Therefore stop the form submission.
event.preventDefault(); // --> This stops the form submit from happening.
} else {
// The user agreed. There is no else block needed, then normal form submission may occur.
}
});
This code is much simpler and easier to read than the snippet in your question. Of course, if you prefer using any other means of asking confirmation from the user, that works too. Just make sure you end up with an if(someboolean) { event.preventDefault(); } at the end of it.
I've created a JSfiddle for you here
I'm hoping you pulled out some relevant code, because your post function was setup incorrectly. I got it working like this:
$(function () {
var deleteLinkObj;
// delete Link
$('.delete').click(function () {
deleteLinkObj = $(this); //for future use
$('#delete-dialog').dialog('open');
return false; // prevents the default behaviour
});
//definition of the delete dialog.
$('#delete-dialog').dialog({
autoOpen: false, width: 400, resizable: false, modal: true, //Dialog options
buttons: {
"Continue": function () {
$.post(deleteLinkObj[0].href, function (data) {
//do the data parsing here
alert(data);
});
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
});
Where you see do the data parsing here is where you need to handle what your controller is returning. Normally, when I do something like this, my return from the delete action on the controller is a boolean value, so that in the Jquery above, you could do something like
if (data == true)
alert("success!");
else
alert("error");
Try this:
<script type="text/javascript">
$(document).ready(function () {
$('form[action$="/Delete"]').submit(function () {
return confirm('Are you sure you want to delete ?');
});
});
</script>
Think that's about all, using jQuery events.. http://api.jquery.com/submit/
I am trying to take the user to login page after cookies are cleared.
I am making a jquery call to my controller to clean the cookies but then I don't know how to redirect him to login page.
I am currently have this code inside my javascript:
function()
{
$.post('/Home/Action', function(result) {
});
window.location="login";
}
public Action()
{
cookie cleaning code;
}
but the problem is refreshing and cookie cleaning are done at the same time. I want to take the user after cookie cleaning.
Thanks
Why did you put window.location outside $.post callback? Try this:
function() {
$.post('/Home/Action', function(result) {
window.location.href = "login";
});
}
function CleanCookiesAndGotoLogin()
{
$.post('/Home/Action', function(result) {
//you put the relocation here so that it waits for the callback
window.location="/ControllerName/ActionName";
});
};