I have an input type="button"
<input type="button" name="DeleteJob" runat="server" value="Löschen" onclick="DeleteJob()" />
and JavaScript method:
function DeleteJob() {
if (confirm("Do you really want to delete selected job/s?"))
return true;
else
return false;
}
How can I instead return true, redirect to Action DeleteJob?
[HttpGet]
public ActionResult DeleteJob(string selectedObject)
{
return View();
}
This question is related to
c#
javascript
asp.net-mvc
redirect
Use the @Url.Action method. This will work and determines the correct route regardless of what IIS server you deploy to.
Example- window.location.href="@Url.Action("Action", "Controller")";
so in the case of the Index action on the Home controller - window.location.href="@Url.Action("Index", "Home")";
(This is more of a comment but I can't comment because of the low reputation, somebody might find these useful)
If you're in sth.com/product and you want to redirect to sth.com/product/index use
window.location.href = "index";
If you want to redirect to sth.com/home
window.location.href = "/home";
and if you want you want to redirect to sth.com/home/index
window.location.href = "/home/index";
I wish that I could just comment on yojimbo87's answer to post this, but I don't have enough reputation to comment yet. It was pointed out that this relative path only works from the root:
window.location.href = "/{controller}/{action}/{params}";
Just wanted to confirm that you can use @Url.Content to provide the absolute path:
function DeleteJob() {
if (confirm("Do you really want to delete selected job/s?"))
window.location.href = '@Url.Content("~/{controller}/{action}/{params}")';
else
return false;
}
I struggled with this a little because I wanted to use Knockout to bind the button to the click event. Here's my button and the relevant function from inside my view model.
<a class="btn btn-secondary showBusy" data-bind="click: back">Back to Dashboard</a>
var vm = function () {
...
self.back = function() {
window.location.href = '@Url.Action("LicenseDashboard", "Application")';
}
}
Youcan either send a Ajax request to server or use window.location to that url.
Maybe better to make an anchor with DeleteJob url instead of button?
<a href="<%=Url.Action("DeleteJob", "YourController", new {selectedObject="someObject"})%>" onclick="return DeleteJob()">Löschen</a>
and use your javascript you wrote already:
function DeleteJob() {
if (confirm("Do you really want to delete selected job/s?"))
return true;
else
return false;
}
So if function return true - you will be redirected. If function return false - you still stay on the page.
function DeleteJob() {
if (confirm("Do you really want to delete selected job/s?"))
window.location.href = "/{controller}/{action}/{params}";
else
return false;
}
Source: Stackoverflow.com