1 year ago

#378746

test-img

Matt M

MVC Url.Action Href onclick Confirmation not preventing redirect

Problem: The onclick="return confirm('Are you sure?')" HTML Attribute in my Href always deletes tag regardless of choice selected by user.

Below is a snippet of my DeleteTag.cshtml file. I am using Url.Action to produce a path to a given tag to be deleted. I am using an @ anchor tag in order to use the url return by Url.Action.

if (tag.CreatedByUserId == Model.ActiveUserId)
{
  // /Content/DeleteTag/5329
  var deleteUrl = Url.Action(MVC.Content.DeleteTag(tag.TagId));
  <a href="@deleteUrl" class="cw-delete-tag-link" rel="tagLocatorClass" onclick="return confirm('Are you sure?')" title="Delete this tag"><img src="../../public/images/icons/silk/delete.png" alt="Delete" /></a>
}

When this url is hit (regardless of continue or cancel), the following code executes.

[RequireAuthorization(MinAccessLevel = Roles.Admin)]
[HttpPost]
public virtual ActionResult DeleteTag(int id) 
{
  ContentAdminService.DeleteTag(id);

  if (Request.IsAjaxRequest()) {
    return Json(id, JsonRequestBehavior.AllowGet);
  } else {
    this.FeedbackInfo("Tag deleted");
    return View();
  }
}

Here the confirmation message is prompted and my choice is cancel. enter image description here

Here the code is still hit even though I selected cancel. enter image description here

I am expecting onclick to return false if I select cancel, and the url should not be hit, and the delete tag code should not be executed.

Perhaps there is something I am misunderstanding.

EDIT: I have also tried onclick='return false;' which still results in the execution of the delete tag action result

javascript

asp.net-mvc

razor

href

confirm

0 Answers

Your Answer

Accepted video resources