MVC post losing values when submitted via javascript - javascript

I have an MVC form with a submit button:
<form method="POST" id="submitProject" action="#Url.Action(SubmitProject, "ProjectSummary")">
<button type="submit" name="submitButton" id="submitProject" value="saveToProposed" class="btn btn-primary">Submit Project</button>
</form>
But when a user clicks on that button i want to show them a confirmation dialog before the post goes on its way:
$('#submitProject').submit(function (e) {
var currentForm = this;
e.preventDefault();
bootbox.dialog({
message: "Approve or Reject",
title: "Project Approval",
buttons: {
success: {
label: "Approve",
className: "btn-success",
callback: function () {
alert("Approved");
currentForm.submit();
}
},
danger: {
label: "Reject",
className: "btn-danger",
callback: function () {
alert("Rejected");
currentForm.submit();
}
},
main: {
label: "Cancel",
className: "btn-primary",
callback: function () {
return true;
}
}
}
});
});
in my controller i am trying to trap the value of the submit button like this:
[HttpPost]
public ActionResult SubmitProject(ProjectModel m, string submitButton)
{
}
if i do not have that preventDefault line in there i can see the value of the submitButton in the controller. With the preventDefault the value is always null.
this is something i have been struggling with for some time as i try to learn MVC. if i didn't have any client side interaction i would be fine. But trying to get js to play with mvc is giving me hearburn. what am i doing wrong?

A form only posts back the name/value pair of its submit button that was clicked. In your case your cancelling the buttons .click() event and then calling the .submit() function (i.e. the submit is no longer triggered by the click so its value is not sent in the request).
Rather than calling e.preventDefault();, call a function that returns true or false, in the same way that you can use the javascript .confirm() function to cancel the form submission (i.e. return confirm("...");
function confirmSubmit()
{
bootbox.dialog({
....
// for the success and danger buttons - return true;
// for the main button - return false
buttons: {
success: {
label: "Approve",
className: "btn-success",
callback: function () {
return true;
}
},
....
});
}
$('#submitProject').submit(function (e) {
return confirmSubmit();
});
Side note: your form only has one submit button, so the value of string submitButton will only ever be "saveToProposed". Not sure if you omitted it from your code, but I assume you would really have at least 2 submit buttons.

Related

re-execute button click after event.preventDefault();

I am generating rows dynamically for a table using ASP.NET Core Razor Pages and each row has a Delete button without button ID.
example of generated HTML for a row:
<button onclick="return DeleteRowConfirm(event);" data-ajax="true" data-ajax-method="GET" data-ajax-begin="AjaxOnBegin" data-ajax-complete="AjaxOnComplete" data-ajax-failure="failed" data-ajax-update="#div_BusyIndicator" href="/ApproveNumber/a10b0c7a?handler=DeleteRow">Delete Row</button>
on button click I am using bootbox.js to confirm using this code:
function DeleteRowConfirm(e) {
e.preventDefault();
bootbox.confirm({
message: "Delete Row?",
buttons: {
confirm: {
label: 'Yes',
className: 'btn-success'
},
cancel: {
label: 'No',
className: 'btn-danger'
}
},
callback: function (result) {
if (result === false) {
}
else {
//$(this).trigger(e.type); //Doe not working
}
}
});
}
I would like to execute the "Button Click" if the user press "Yes".
I have tried $(this).trigger(e.type); but it does not working.
I solved the problem with the help of #mousetail and "Pooma" from this link https://stackoverflow.com/a/48018708
I have replaced button element to element and for onclick I have set event.preventDefault(); event.stopImmediatePropagation(); DeleteRowConfirm(event);
at DeleteRowConfirm function when callback is true I have removed the onclick from the element so it does not loop with bootbox popup and than trigger the click event.
$(e.target).removeAttr('onclick');
$(e.target).trigger(e.type);

jquery-confirm pause script if more than one $.confirm are present

I've a form with submit validation.
I'dd like to add more than 1 alerts on form submit with:
var proceed = true;
$.confirm({
title: 'Confirm 1',content: 'No products added. Are you sure to proceed?',
buttons: {
ok: {
text: "OK",
btnClass: 'btn-success',
action: function () {
}
},
cancel: {
text: "Cancel",
action: function () {
proceed = false;
return false;
}
}
}
});
... some others checks ....
if ( !proceed ) { return false;} //EXIT SCRIPT
// IF ALL CHECKS PASSED
$.confirm({
title: 'Final confirm',content: 'All checks are ok. Are you sure to insert?',
buttons: {
ok: {
text: "OK",
btnClass: 'btn-success',
action: function () {
form.submit(); //SUBMIT THE FORM
}
},
cancel: {
text: "Cancel",
action: function () {
// CLOSE DIALOG
}
}
}
});
but on form submit I get all of 2 $.confirm opens! I'd like to pause second one until I click OK on the first one.
My jsfiddle https://jsfiddle.net/st1cqb39/2/
Make the finalConfirm function as a generic one, and call it in the action callback (of your empty check) accordingly.
Here is a DEMO: https://jsfiddle.net/st1cqb39/3/
Hope this helps!

Bootbox submit confirmation. Why onclick runs before submit even when it's ran with preventDefault()?

I've been trying to implement a confirmation box before submitting the form data.(Mind you, the default confirmation box is out of question due to lack of customization.)
As of right now I have this code using Bootbox.min.js:
https://codepen.io/IdontCommentMyCode/pen/XzEaMB
function thatFunction() {
bootbox.confirm({
message: "CUIDADO! Ao proceder podera perder dados. <br> Pretende avançar?",
size: "small",
buttons: {
confirm: {
label: 'Sim',
className: 'btn-success'
},
cancel: {
label: 'Não',
className: 'btn-danger'
}
},
callback: function(result) {
console.log('This was logged in the callback: ' + result); //Função default para demonstração do funcionamento
$('from1').submit(function(e) {
var currentForm = this; // Necessário
e.preventDefault(); // Previne o Submit do botão original
bootbox.confirm("Are you sure?", function(result) {
if (result) { // Se callback === True então o Form é submetido
currentForm.submit();
}
});
});
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
<input class="btn btn-warning paddy" id="form1" onclick="thatFunction()" type="submit"></input>
What happens when I click the button is that the submission is made before the onclick function is ran. Which results in the forms being submitted and the confirmation only after it happens. From my understanding, the function runs, prevents out the default type="submit" and only after confirmation the form is submitted. Is my logic right at this current situation?
Aside from this issue, one of my questions was:
Is it possible, using a function, to turn a button into type="submit" and submit it at the end of the same function?

handling Multiple buttons in $ionicPopup prompt

The documentation says:
Show a simple prompt popup, which has an input, OK button, and Cancel
button. Resolves the promise with the value of the input if the user
presses OK, and with undefined if the user presses Cancel.
I was doing:
$ionicPopup.prompt({
//options
}).then(function (userinput) {
//get userinput and send to server
});
I need to add a third button, but can't get the text of the input, how can I resolve the promise on the onTap event of the button to get the input?
$ionicPopup.prompt({
title: '¿Are you sure?',
inputType: 'text',
buttons: [
{ text: 'Cancel'
//close popup and do nothing
},
{
text: 'NO',
type: 'button-assertive',
onTap: function(e) {
//send to server response NO
}
},
{
text: 'YES',
type: 'button-energized',
onTap: function(e) {
//get user input and send to server
}
}]
See this demo i made with your code: http://play.ionic.io/app/ac79490c8914
prompt() is not meant to add more than two buttons,show() is used to make complex pop ups, Please see show() method in same documentation. As written in documentation, i am quoting:
Show a complex popup. This is the master show function
for all popups.
A complex popup has a buttons array, with each button having a text
and type field, in addition to an onTap function.
Your code will be like:
$scope.showPop = function(){
$scope.data = {};
var myPopup = $ionicPopup.show({
template: '<input type="text" ng-model="data.myData">',
title: '¿Are you sure?',
scope: $scope,
buttons: [
{ text: 'Cancel'
//close popup and do nothing
},
{
text: 'NO',
type: 'button-assertive',
onTap: function(e) {
return null;
}
},
{
text: 'YES',
type: 'button-energized',
onTap: function(e) {
return $scope.data.myData;
}
}]
});
myPopup.then(function(userinput) {
if(userinput){
console.log('returned data'+ userinput)
}
});
}
Simple thing about above code is that you have bind input with $scope (<input type="text" ng-model="data.myData">) so you can access it in any manner.

Bootbox: Callback function after dismissing the dialog / Clicking on the 'X' button

The following snippet allows me to perform stuff in a callback function for the buttons that are clicked. However, how can I get a callback function, or a similar workaround such that I can perform some code when a user clicks on the 'X' button/dismisses the dialog?
bootbox.dialog({
title: "Woah this acts like an alert",
message: "Cool info for you. You MUST click Ok.",
buttons: {
sucess:{
label: "Ok",
callback: callback
}
}
});
callback(){//stuff that happens when they click Ok.}
I do not want to disable/hide the close button with
closeButton: false,
There is onEscape function for this.
bootbox.dialog({
message: 'the msg',
title: "Title",
onEscape: function() {
// you can do anything here you want when the user dismisses dialog
}
});
You can use a variable to check if the modal was hidden after a click on OK or x button / escape key
var status = false;
$('.btn').on('click', function () {
bootbox.dialog({
title: "Woah this acts like an alert",
message: "Cool info for you. You MUST click Ok.",
buttons: {
sucess: {
label: "Ok",
callback: function () {
status = true;
}
}
},
onEscape: function () {
$('.bootbox.modal').modal('hide');
}
});
});
$(document).on("hidden.bs.modal", ".bootbox.modal", function (e) {
callback();
});
function callback() {
if (!status) {
onClose();
} else {
onOK();
status = false;
}
}
function onClose() {
$('p.alert span').removeClass().addClass('text-danger').text("Dismissed");
}
function onOK() {
$('p.alert span').removeClass().addClass('text-success').text("Sucess");
}
Fiddle demo
Some people might see this as a bit of a hack-around. Although it suits me fine as all I wanted to acknowledge as a developer that someone accepted the message, which triggered the next event.
Using Bootbox.js' native confirm() method which does supply a callback action. I added an additional class as an option to the confirm button (which must be supplied on a confirm() call) with the hidden classname (E.g. Bootstap has a helper class for display:none called hidden.
This hides the confirm button, thus the Modal appears as a normal Alert box.
bootbox.confirm({
message: "Some Button Text",
buttons: {
"cancel": {
label: "<i class='fa fa-check'></i> OK - I understand",
className: "btn btn-primary"
},
//Hide the required confirm button.
"confirm": { label: "", className: "hidden" }
},
callback: function(){
//Begin Callback
alert( "Finished" );
}
});
JsFiddle Example

Categories

Resources