process to mvc action after jquery confirmation button is clicked - c#

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/

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.

jQuery modal dialog first open works, subsequent opens fail

I've got an MVC project written in C# using Razor Engine. I'm calling a modal through jQuery which loads a form to POST fields to my controller via AJAX, returning updated content that loads into the calling DIV.
This works wonderfully ... once. Attempting to open the modal again (to edit a different row), the form loads into the browser as if redirected, rather than displaying it in a modal dialog.
In my view, I'm calling my modal from a link (Custom HTML Helper, line breaks added only for readability):
#Html.NoEncodeActionLink("<span class='glyphicon glyphicon-pencil'></span>", "Edit Phone", "Edit", "PhoneLinks",
theseRouteValues: new { id = item.id },
theseHtmlAttributes: new {
data_modal = "",
data_toggle = "modal",
data_dismiss = "modal",
data_title = "Edit Phone",
data_btnlabel = "Edit Phone",
data_callingdiv = "replaceTargetPhone",
data_whichform = "PhoneLinkModalForm",
#class = "btn btn-primary btn-xs"
}
)
Clicks on the link are caught in my jQuery and handled there with AJAX.
jQuery(function () {
jQuery.ajaxSetup({ cache: false });
// Initialize the modal DIV
var $modalDiv = jQuery("<div class='modalContent'></div>")
.appendTo('body')
.dialog({
modal: true,
autoOpen: false,
position: { my: 'center', at: 'center', collision: 'fit' },
show: { effect: 'blind', duration: 300 },
hide: { effect: 'explode', duration: 500 },
close: function () { jQuery('div.modalContent').empty(); }
});
// Create a modal popup when a modal-generating link is clicked
jQuery("a[data-modal]").on("click", function (e) {
e.preventDefault();
// Gather parameters from the link into variables for readability
var sourceLink = jQuery(this);
var sourceHref = sourceLink.attr('href'); // Relative path to controller method
var titleData = sourceLink.data('title'); // Title for the modal dialog
var callingDiv = "#" + sourceLink.data('callingdiv'); // #replaceTarget divs ... where to apply refresh after AJAX returns
var whichForm = "#" + sourceLink.data('whichform'); // ID of the form called by the link that will be submitted in the modal
var btnProceed = sourceLink.data('btnlabel'); // Which function was called: Create/Edit/Delete (for button labelling)
var btnCancel = "Cancel";
var theseButtons = {};
// Submit Button
theseButtons[btnProceed] = function () {
// Send parameters to another function for processing
// On success, the processForm() function closes the modal
processForm(theModalContent, callingDiv, theModalContainer, sourceHref, whichForm, titleData);
};
// Cancel Button
theseButtons[btnCancel] = function () {
jQuery('div.modalContent').empty().dialog('close');
return false;
};
// Add a few parameters to the modal (title, buttons, etc.) and load content
$modalDiv.empty();
$modalDiv
.load(sourceHref)
.dialog({
title: titleData,
buttons: theseButtons
});
$modalDiv.dialog('open');
});
});
The processForm() function handles the AJAX call to the controller, and it works as expected. On success, it closes the modal with the same line of code in the Cancel button:
jQuery('div.modalContent').empty().dialog('close');
I can open the modal the first time without issue.
First call to modal works perfectly.
I can cancel the modal and reopen it as many times as I want.
If I submit the form in the modal, the form is processed correctly, my database updates correctly, and the content reloads in the target DIV correctly. However, if I then try to open a subsequent modal (for editing another phone number), the form doesn't load into a modal. It instead loads as the body of a new HTML document.
Second call to modal fails.
I have tried closing the modal in many different ways:
.dialog('destroy')
or
.remove()
or
.dialog('destroy').remove()
I have also tried initializing the modal within the "a[data-modal].on('click') function, rather than initializing on document ready.
All working variations work the first time, then fail after the first submit.
Any suggestions are greatly appreciated!
UPDATE: Added processForm() function code.
function processForm(thisModalContent, thisCallingDiv, thisModalContainer, thisMethod, thisForm, thisTitle) {
// Capture the form fields
var formPost = jQuery(thisForm);
// Serialize the fields to an array
// This step is necessary to handle phone number mask removal
var values = formPost.serializeArray();
// Some code here removes phone masking and
// puts the raw numbers back into the array
// Convert the serialized array to a single string for POST
var serializedPost = jQuery.param(values);
// Send data to controller and handle response
jQuery.ajax({
url: thisMethod,
type: 'POST',
data: serializedPost,
error: function (x, e) {
if (x.status === 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status === 404) {
alert('Requested URL not found.');
} else if (x.status === 500) {
alert('Internal Server Error.\n DataSent: \n' + serializedPost + '\n Response Text: \n' + x.responseText);
} else if (e === 'parsererror') {
alert('Error.\nParsing JSON Request failed.\n' + x.responseJSON);
} else if (e === 'timeout') {
alert('Request Time out.');
} else {
alert('Unknown Error.\n' + x.responseText);
}
},
success: function (result) {
if (result.success) {
//jQuery('div.modalContent').dialog('destroy').remove(); // Didn't Work
//jQuery('div.modalContent').dialog('destroy'); // Didn't Work
//jQuery('div.modalContent').remove(); // Didn't Work
jQuery('div.modalContent').empty().dialog('close');
jQuery(thisCallingDiv).load(result.url);
} else {
thisModalContent.html(result);
}
}
});
return false;
}
Also, it's worth mentioning that while the code in this example is referencing phone numbers, I have a DIV for addresses on the same page. The Address editing link click calls the same jQuery modal.
If I submit a phone edit, subsequent calls to the modal from phone edit links are broken.
BUT I can successfully call the address edit modal ... once. Then subsequent calls to it are broken.
Refreshing the page fixes the modal from both link types (phones and addresses). Both types can be opened and cancelled repeatedly until one is submitted. Then that one is broken, but the other still works until it is submitted.

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 create the confirm box in mvc controller?

I need to create the confirm box in mvc controller?. Using this 'yes' or 'no' value I need to perform the action in my controller. How we do that?
Sample code:
public ActionResult ActionName(passing value)
{
// some code
message box here
if (true)
{ true code}
else { else code}
}
You can do this with ActionLink
#Html.ActionLink(
"Delete",
"DeleteAction",
"Product",
new { confirm = true, other_parameter = "some_more_parameter" },
new { onclick = "return confirm('Do you really want to delete this product?')" })
If user confirm, then link parameter will pass to the controller action method.
public ActionResult DeleteAction(bool confirm, string other_parameter)
{
// if user confirm to delete then this action will fire
// and you can pass true value. If not, then it is already not confirmed.
return View();
}
Update
You can not show message box in controller side. But you can do this like following
public ActionResult ActionName(passing value)
{
// some code
message box here
if (true){ ViewBag.Status = true }
else { ViewBag.Status = false}
return View();
}
And view
<script type="text/javascript">
function() {
var status = '#ViewBag.Status';
if (status) {
alert("success");
} else {
alert("error");
}
}
</script>
But these all codes are not elegant way. This is solution of your scenerio.
Yes, you can do this with #Html.ActionLink as AliRıza Adıyahşi has commented.
Subscribe to the onclick event of the #Html.ActionLink
Here is the implementation:
#Html.ActionLink("Click here","ActionName","ControllerName",new { #onclick="return Submit();"})
And in javascript write the confirm box.
<script type="text/javascript">
function Submit() {
if (confirm("Are you sure you want to submit ?")) {
return true;
} else {
return false;
}
}
</script>
Edit
Try like this:
<script type="text/javascript">
function Submit() {
if (confirm("Are you sure you want to submit ?")) {
document.getElementById('anchortag').href += "?isTrue=true";
} else {
document.getElementById('anchortag').href += "?isTrue=false";
}
return true;
}
</script>
#Html.ActionLink("Submit", "Somemethod", "Home", new { #onclick = "return Submit();", id = "anchortag" })
Now in your controller do some operations based on the isTrue querystring
public ActionResult Somemethod(bool isTrue)
{
if (isTrue)
{
//do something
}
else
{
//do something
}
return View();
}
You dont create confirm box in a Controller, but yes in a View, using JQuery Dialog.
The Controller is already inside the server, so you don't have user interactions there.
Your View, in the other hand, is the place where the user will choose options, type information, click on buttons etc...
You can intercept the button click, to show that dialog, and only submit the post when the option "Yes" gets clicked.
JQuery Dialog requires jquery.js, jquery-ui.js, jquery.ui.dialog.js scripts referenced in your page.
Example:
$(function(){
$("#buttonID").click(function(event) {
event.preventDefault();
$('<div title="Confirm Box"></div>').dialog({
open: function (event, ui) {
$(this).html("Yes or No question?");
},
close: function () {
$(this).remove();
},
resizable: false,
height: 140,
modal: true,
buttons: {
'Yes': function () {
$(this).dialog('close');
$.post('url/theValueYouWantToPass');
},
'No': function () {
$(this).dialog('close');
$.post('url/theOtherValueYouWantToPAss');
}
}
});
});
});
I can confirm that AliRıza Adıyahşi's solution works well.
You can also customize the the message. In my case we're using MVC and Razor, so I could do this:
<td>
#Html.ActionLink("Delete",
"DeleteTag", new { id = t.IDTag },
new { onclick = "return confirm('Do you really want to delete the tag " + #t.Tag + "?')" })
</td>
Which showed a dialog with a specific record named in it. Might also be possible to give the confirm dialog a title, haven't tried that yet.
<a href="#Url.Action("DeleteBlog", new {id = #post.PostId})" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">
<i class="glyphicon glyphicon-remove"></i> Delete

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