MVC: Javascript confirm for delete action not working - javascript

I'm pretty new to MVC and Javascript; I'm trying to make a delete action work; I'm using an ActionLink with a Javascript function for confirmation. The JAvascript confirm doesn't work, the delete action is fired even when I press Cancel; additionally, I cannot seem to be able to use [HttpDelete] verb for the action: I need to pass two parameters to the Delete action but after applying #Html.HttpMethodOverride(Http.Delete) on the action link it searches
for an URL with just one parmaeter: id.
Here is my code: action link
#Html.HttpMethodOverride(HttpVerbs.Delete)
#Html.ActionLink(
"Delete",
"Delete",
new {id=notification.Id, typeId=notification.TypeId},
new {onclick="confirmDeleteAction()"})
function confirmDeleteAction() {
return confirm('Are you sure you want to delete the notification ?');
}
Delete action:
[HttpDelete]
public ActionResult Delete(int id, int typeId)
{
Service.DeleteNotification(id, typeId);
NewIndexViewModel model = Service.GetNewIndexViewModel();
return View("Index", model);
}

Try this
#Html.ActionLink(
"Delete",
"Delete",
new {id=notification.Id, typeId=notification.TypeId},
new {onclick="return confirmDeleteAction();"})

You need to cancel the default behaviour of the browser when the user clicks cancel. You can do this by returning the result of confirmDeleteAction() to your <a> tag:
#Html.ActionLink(
"Delete",
"Delete",
new {id=notification.Id, typeId=notification.TypeId},
new {onclick="return confirmDeleteAction()"})
For clarity, I added the return keyword to your onclick handler which will return the result of confirmDeleteAction() to the browser -
true = perform the default behaviour of the link
false = do nothing

You can do this type by also.
#Html.ActionLink(
"Delete",
"Delete",
new {id=notification.Id, typeId=notification.TypeId},
new {onclick="confirmDeleteAction(" + notification.Id + ")" })
function OnDeleteClick(id) {
var ActionID = id;
var flag = confirm('Are you sure you want to delete this record?');
if (flag) {
return true;
}
else{
return false;
}

Related

"How to 'Reload the only Partial View' part after submitting the form with HTML Helper in jquery?"

I have a partial view on a View of MVC so after Submit the form that is submitting within jquery that you can see below in the code. I have to refresh the Partial view to show some changes that made in partial view after clicking on save button. What should I do in the section of script on click of save?
#using(Html.BeginForm(FormMethod.Post, new{id="form"}))
{
<div>
#Html.Partial("_VehicleCard", Model)
</div>
<div>
<div id="submitBtn" class="row>
#(Model.VehicleCards.Count>0?"":"hidden")">
<div>
<button type="button" id="btnSubmit">Save</button>
</div>
</div>
</div>
}
#section scripts{
<script>
$('#btnSubmit').click(function (event) {
event.preventDefault();
event.stopImmediatePropagation();
$('#form').submit();
//here i wants to refresh Patrial View.
});
</script>
}
Here is my Controller code:
public PartialViewResult GetVehicleForEndMileage(string date, int? Id)
{
try
{
var model = new VehicleEndMilageVM();
DateTime selectedDate;
DateTime.TryParseExact(date, "dd/MM/yyyy", null,
DateTimeStyles.None, out selectedDate);
model.SelectedDate = selectedDate.ToString("dd/MM/yyyy");
model.LocationId = Id ?? 0;
model.VehicleCards =
vehicleDailyInspectionBLL.GetDailyInspectionDetail(selectedDate, Id).Select(x => new VehicleCard
{
VehicleNumber = x.VehicleNumber,
StartMilage = x.StartMilage,
Driver = x.Driver,
EndMilage = x.EndMilage,
VehicleId = x.VehicleId,
VehicleDailyInspectionId = x.VehicleDailyInspectionId,
IsEndMilageAdded = (x.EndMilage !=null && x.EndMilage > 0) ? true : false
}).ToList();
return PartialView("_VehicleCard", model);
}
catch (Exception ex)
{
throw;
}
}
You can simply do it via an ajax call.
First, you have to set an id for <div> tag
<div id="htmlContainer">
#Html.Partial("_VehicleCard", Model)
</div>
Then
$('#btnSubmit').click(function (event) {
event.preventDefault();
event.stopImmediatePropagation();
$('#form').submit();
$.ajax({
url: 'url',
dataType: 'html',
success: function(data) {
$('#htmlContainer').html(data);
}
});
});
You controller seems to be like this :
public PartialViewResult GetVehicleCard(...)
{
return PartialView("_VehicleCard", your view model);
}
HttpPost methods are for SENDING data to the server. You do not need to send your data to the server, rather, you need to GET data from the server with specified criteria and then display it. With that being send, you do not need your HTML.BeginForm() method. Moreover, you do not need to declare a PartialViewResult return type, an ActionResult will suffice. Additionally, you don't need to return the the name of the partial view and the associated model. Simply give the partial view the model results like so:
return PartialView(model)
Next, create an AJAX link on the page you will be clicking your button on like so:
#Ajax.ActionLink("GetVehicleForEndMileage", "Vehicles", new AjaxOptions()
{
HttpMethod = "GET",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "Results"
})
<div id="Results"></div>
You can wrap this link in a button tag to work with your current set-up.
Now just define your Partial View in a separate .cshtml file.
#model ModelName
<div>
// Model attributes to be displayed here.
</div>
Now, embed that partial view within the view you wish to have the callback displayed.
Having said all of that, your javascript/jQuery can be removed.

How to invoke my post method when I'm changing dropdown list in ASP.NET MVC

I'm very new to MVC and Javascript so please be patient with me, I'm working on small application and I came to part when I need to select something from dropdown list and based on that selection I need to redirect user to another View, I also need to determine somehow where I should redirect user, so that is reason why I tried to pass parameter also ( database ID to my post method) but unfortunatelly this is not working, in section below I will post my code:
Method which is sending data to my DropDownList :
public ActionResult ShowArticleGroup()
{
List<ArticleGroup> articlesGroups = GroupsController.GetAllGroups();
ViewBag.articlesGroups = articlesGroups;
return View(articlesGroups);
}
[HttpPost]
public ActionResult ShowArticleGroup(string id)
{
//Here I wanted to take ID of selected Group and because there will be allways 3 Groups I can do if else and Redirect by ID
if(id =="00000000-0000-0000-0000-000000000002")
{
return RedirectToAction("Create","Article");
}
return RedirectToAction("Create", "Article");
}
And my VIEW - there is only one control on the view : just one dropdown, and based on selection I should be redirected to another view, and I wanted here to take ID of selected group and by that I wanted to redirect user to appropiate view:
#model IEnumerable<Model.ArticleGroup>
#{
ViewBag.Title = "Add new article";
}
<h3 style="text-align:center">Choose article group</h3>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
<div class="form-group" style="text-align:center">
#Html.DropDownList("Group", new SelectList(ViewBag.articlesGroups, "GroupID", "GroupTitle.Name"), null, new { onchange = "document.location.href = '/Articles/ShowArticleGroup/' + this.options[this.selectedIndex].value;" })
</div>
</div>
}
First of all, usage of location.href on DropDownList seems wrong here:
#Html.DropDownList("Group", new SelectList(ViewBag.articlesGroups, "GroupID", "GroupTitle.Name"), null,
new { onchange = "document.location.href = '/Articles/ShowArticleGroup/' + this.options[this.selectedIndex].value;" })
AFAIK, location.href used for redirect to another page using HTTP GET, hence it will try to call first ShowArticleGroup action method without parameter, and the URL parameter simply ignored since given URL parameter only exist in POST.
To submit the form with DropDownList, you need to handle change event triggering POST into controller action method:
jQuery
<script type="text/javascript">
$(document).ready(function() {
$("#Group").change(function() {
var groupId = $("#Group").val();
$.post('#Url.Action("ShowArticleGroup", "ControllerName")', { id: groupId }, function (response, status) {
// response handling (optional)
});
});
});
</script>
DropDownList
#Html.DropDownList("Group", new SelectList(ViewBag.articlesGroups, "GroupID", "GroupTitle.Name"), null)
I recommend you using strongly-typed DropDownListFor with binding to a viewmodel approach if you want to pass viewmodel contents during form submit.
NB: $.post is shorthand version of $.ajax which uses POST submit method as default.
Related issues:
Autopost back in mvc drop down list
MVC 4 postback on Dropdownlist change

how to open view result from action call from javascript

i'm developing using ASP.Net mvc 4. I have a delete function in my Index view. Before user proceed to delete an item, this is the steps to go through
pop-up a confirm dialog to get the 'yes' or 'no' answer using javascript.
If the user say 'yes', I call the delete action from my controller
the delete action remove the item from database
the delete action return 'RedirectToAction ("Index");'
.. suppose the view will be updated with latest update
Step 5 is my problem.. its not working
Here is my code
The delete button
<a href="#Url.Action("DeleteFile", new { id = #item.Id })"
onclick = "return confirm2delete(this);"
class="btn btn-danger btn-sm"
data-toggle="tooltip" title="Delete File">
<i class="fa fa-trash-o"></i>
</a>
The javascript
function confirm2delete(obj)
{
deleteLinkObj = $(this);
w2confirm("Are sure to delete this file ?")
.yes(function () {
$.get(obj.href, function (data) {
alert(data); // i checked ..this return the html page created from the delete action
window.open (data); // not the right approach ???
});
})
.no(function () {
alert("no");
result = false;
});
return false;
}
The delete action in my controller
public ActionResult DeleteFile(int id)
{
FileUpload f = db.FileUploads.Find(id);
try
{
FileInfo dfile = new FileInfo(f.fileUrl);
if (dfile.Exists) { dfile.Delete(); }
fileUrl = f.FileUrl.Replace("Images/Uploads", "Images/Thumbnails");
FileInfo thumbnail= new FileInfo(fileUrl);
if (thumbnail.Exists) { thumbnail.Delete(); }
db.FileUploads.Remove(f);
db.SaveChanges();
}
catch (Exception ex)
{
}
return RedirectToAction("Index"); // or may i should return something else to make it work in javascript ???
}
Hope you guys can help me. I've been searching and trying for days to come to this level and I feel its time get some help. Just a little bit more. Almost there.
Ajax calls stay in the same page, so calling return RedirectToAction("Index"); is pointless (it will not redirect). In any case it is unnecessary to return the new view. Instead you can just remove the existing elements from the DOM if the controller successfully deleted the item. You have not shown your view, but assuming you have a table where a row might be something like
<tr>
<td>the name of the file</td>
<td>the delete link</td>
</td>
Then you can use the following where the 'delete' link is
<td><button type="button" class="delete" data-id="#item.Id">Delete</button></td>
The key points are the class and the data-id attributes - modify the rest to suit your display but remove the onclick attribute (stop polluting you markup with behavior and use unobtrusive javascript - its the 21st century!)
Then the script
var url = '#Url.Action("DeleteFile")';
$('.delete').click(function() {
var id = $(this).data('id');
var row = $(this).closest('tr'); // modify if the containing element is not a <tr>
w2confirm("Are sure to delete this file ?")
.yes(function () {
$.post(url, { id: id }, function(response) { // its a POST, not a GET!
if (response) {
row.remove(); // remove the row
} else {
// Oops, something went wrong
}
}).fail(function (response) {
// Oops, something went wrong
});
})
.no(function() {
alert("no");
});
});
Note if your using jquery version 1.9+ then the else block in the $.post() functuion is not required since return Json(null); in the method below will go to the .fail() callback
Then in the controller, return json to indicate the item was successfully deleted
[HttpPost]
public ActionResult DeleteFile(int id)
{
FileUpload f = db.FileUploads.Find(id);
try
{
....
db.SaveChanges();
return Json(true); // signal success
}
catch (Exception ex)
{
return Json(null); // signal failure
}
}

ASP.NET MVC onclick confirm if false redirects to an action even different one

I have a link in partial view, which is an easy list of items which I can open to edit/delete.
The link to delete has confirm
- when I press OK, everything is fine
- when I press cancel, it redirects it anyway but not even to the Delete controller's action but to the Detail.
EDIT
this one redirects to the DETAIL always => doesnt delete anything
Delete
this one redirects to detail only if pressed cancel => deletes when OK, doesnt work on cancel
#Html.ActionLink("Delete", "Delete", "Items", new { id = item.ItemID }, new { onclick = "return confirm('Are you sure to delete this item?')" })
I have tried it without the return false, putting to onclick return confirm(..), but nothing seems to work and if I press cancel I end up redirected to /Items/Detail/ID, which I completely dont understand and the delete method in the controller is not called.
controller - detail that is being called if I press cancel
[HttpGet]
public ActionResult Detail(int id)
{
TravelRequest model = DB.TravelRequests.Where(m => m.TravelRequestID == id).FirstOrDefault();
ViewBag.AttachmentFilePath = model.AttachmentFilePath;
SetDetailCommons(model);
return View("Create", model);
}
Delete which does not happen (which is OK because it shoult not be called if I press cancel...)
[HttpGet]
public ActionResult Delete(int id)
{
var model = DB.TravelRequests.Where(m => m.TravelRequestID == id).First();
DB.TravelRequests.Remove(DB.TravelRequests.Where(m => m.TravelRequestID == id).First());
DB.SaveChanges();
return RedirectToAction("Detail", "Assignment", new { id = model.AssignmentID });
}
Thank you for any suggestions :)

Is there any way to call JavaScript in an MVC4 ActionLink for one of the RouteValue parameters?

I have a drop down list (DropDownListFor) and an ActionLink on my page. Basically, the problem I'm having is I'm trying to capture the selected value from my drop down list and passing that into my ActionLink as an ID. Here's my code:
#Html.DropDownListFor(x => x.Capsules, new SelectList(Model.Capsules, "pk", "name", "pk"))
<br />
#Html.ActionLink("Submit", "Create",
new { controller = "Process", id = /*JavaScript here to get the selected ID for the DropDownList above*/ },
new { data_role = "button" })
For what I'm trying to accomplish, is there a way to embed JavaScript into my Html.ActionLink call? If there's not a way, or if it's not recommended, could you please advise of another solution to solve this problem? Thanks in advance!
You can do this via intercepting the link using javascript Darin has posted an example of this.
However, it looks like you're trying to submit some values using an ActionLink, and you're probably better off creating a viewmodel which holds all the values you want, and then posting everything using a submit button. This allows you to post more data than just the ID, prevents you from being dependent on Javascript, and keeps all of the code server side instead of mixing and matching.
Judging by the small code you've posted - you already have a model, probably some strongly typed entity, and it has a property called Capsules.
In your controller, create the view model which holds the view's data:
public class YourViewModel
{
YourModel YourModel { get; set; }
public int CapsuleId { get; set; }
}
Then your view:
#using( #Html.BeginForm( "Create", "Process" ) )
{
#Html.DropDownListFor(m=> m.CapsuleId, new SelectList(Model.YourModel.Capsules, "pk", "name", "pk"))
<input type="submit">
}
Then your controller action to handle this:
[HttpPost]
public ActionResult Create( YourViewModel model )
{
var id = model.CapsuleId;
// do what you're going to do with the id
return View();
}
You can put dummy value for the id parameter like this :
#Html.ActionLink("Submit", "Create",
new { controller = "Process", id = "dummy" },
new { data_role = "button" })
Then replace that value when the link is clicked.
// Assuming your link's id is `submit`, and the dropdown's id is `capsules`
$('#submit').click(function() {
var id = $('capsules').val();
$(this).href = $(this).href.replace('dummy', id);
});

Categories