MVC ActionLink calling multiple JQuery functions - c#

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.

Related

Why does my function stop working without an alert?

So I've got this function right here in my view:
function izbrisi() {
var b = document.getElementById('proizvod').value;
{
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: { id: b }
}).done(function () {
alert('Izbrisan');
});
alert('Izbrisan'); #* bez ovoga se ne brise proizvod *#
}
}
The controller it's passed to:
public ActionResult izbrisiProizvod(int Id)
{
RadniProizvod.IzbrisiProizvod(Id);
return View();
}
And finally the "IzbrisiProizvod" method:
public void IzbrisiProizvod(int IdProizvoda)
{
Proizvod izbrisaniProizvod = azilEntities.Proizvods.FirstOrDefault(x => x.idProizvoda == IdProizvoda);
azilEntities.Proizvods.Remove(izbrisaniProizvod);
azilEntities.SaveChanges();
}
For whatever reason, if I don't add the final alert (the one where there's a comment), the code just will not work. Nothing gets deleted, nothing gets reported to the console. As soon as I add in the final alert, it will magically start working.
Can someone explain this magic to me?
Always write your jquery functions like this, as per documentation. (The always is optional)
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
So in your case:
function izbrisi() {
var b = document.getElementById('proizvod').value;
{
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: { id: b }
}).done(function () {
alert('Izbrisan');
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});
}
}
And maybe change alerts to console log or similar.
Try Network tool within your browser dev tools. For example for Firefox Dev Tools. When you click your element (let's say button) you should see new http request in the list of all request within Network tool. If you don't then your ajax call didn't happen at all or it was happen on previous page because you've experienced page reloading. Check if Proizvod actually deleted. If it is then your js function works but you don't see response. If there is s new http request within Network tool, inspect it a little bit to see what is happen (just click on it and in the right you will see details).
Also, you can open console and instead click the html element type in your console: izbrisi(). Function should execute and if it works you will see a new http request in Network tool and your alert for done will popup. If this is the case then your html element has default behavior on click event. So you should prevent it in order to prevent page reloading. Let say that you use a button for click on it. The button html should look like:
<button onclick="izbrisi(e)">Izbrisi</button>
And the js function:
function izbrisi(e) {
e.preventDefault();
// ... your code goes here
}
For whatever reason, if I don't add the final alert (the one where there's a comment), the code just will not work. Nothing gets deleted, nothing gets reported to the console. As soon as I add in the final alert, it will magically start working.
Your ajax only contains the .done() promise callback. This will only execute if the ajax request receives a 200 success code. You can add in the .fail() promise to with a unique alert to see what is happening.
In your code, the final alert is fired no matter what.
Try this to help see what is going on. Use this fiddle and open your console also. Note the different alert messages in the .done() and .fail() promises.
//var b = document.getElementById('proizvod')?.value;
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: {
id: 'someData'
}
}).done(function() {
alert('success');
}).fail(function() {
alert('error');
});
console.log('i fire no matter what');

Load specific data based on passed Id on link click in ASP.NET

My goal is to build AJAX, which will show details of specific Building when user clicks on specific link <a...>
My Controller
public IActionResult BuildingDetail(int id)
{
return PartialView("_BuildingDetailsPartial", _buildingRepository.GetById(id));
}
My view
#foreach (var employee in Model.employees)
{
...
<a id="LoadBuildingDetail" href="#LoadBuildingDetail" data-assigned-id="#employee.Office.BuildingId"
onclick="AssignButtonClicked(this)">#employee.Office.Name</a>
...
}
Place to show Details of Building when user clicks on link. So _BuildingDetailsPartial will render here.
<div id="BuildingDetail">
</div>
Scripts: Im stuck here. I need to load specific BuildingDetail based on passed id.
<script type="text/javascript">
$(document).ready(function () {
function AssignButtonClicked(buildingId) {
var BuildingId = $(buildingId).data('assigned-id');
}
$("#LoadBuildingDetail").click(function () {
$("#BuildingDetail").load("/employees/buildingdetail/", { id: AssignButtonClicked() }, );
});
})
</script>
The issue is due to the logic of the click handler in jQuery. You're attempting to call a function in the onclick attribute of the element which won't be accessible as it's defined inside the document.ready scope.
Also, you're trying to set the id property of the object you send in the request to a function which has no return value.
To fix this, remove the onclick attribute from the HTML you generate, and just read the data attribute from the element directly in the jQuery event handler before you send the AJAX request. Try this:
#foreach (var employee in Model.employees)
{
<a class="LoadBuildingDetail" href="#LoadBuildingDetail" data-assigned-id="#employee.Office.BuildingId">#employee.Office.Name</a>
}
<script type="text/javascript">
$(function () {
$(".LoadBuildingDetail").click(function () {
$("#BuildingDetail").load("/employees/buildingdetail/", {
id: $(this).data('assigned-id')
});
});
})
</script>

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

process to mvc action after jquery confirmation button is clicked

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/

Categories