How do I redirect a user when a button is clicked?
Solution 1
It depends on what you mean by button. If it is a link:
<%= Html.ActionLink("some text", "actionName", "controllerName") %>
For posting you could use a form:
<% using(Html.BeginForm("actionName", "controllerName")) { %>
<input type="submit" value="Some text" />
<% } %>
And finally if you have a button:
<input type="button" value="Some text" onclick="window.location.href='<%= Url.Action("actionName", "controllerName") %>';" />
Solution 2
Just as an addition to the other answers, here is the razor engine syntax:
<input type="button" value="Some text" onclick="@("window.location.href='" + @Url.Action("actionName", "controllerName") + "'");" />
or
window.location.href = '@Url.Action("actionName", "controllerName")';
Solution 3
If, like me, you don't like to rely on JavaScript for links on buttons. You can also use a anchor and style it like your buttons using CSS.
<a href="/Controller/View" class="Button">Text</a>
Solution 4
if using JQuery, you can do this :
<script type="text/javascript">
$('#buttonid').click(function () {
document.location = '@Url.Action("ActionName","ControllerName")';
});
</script>
Solution 5
It has been my experience that ASP MVC really does not like traditional use of button so much. Instead I use:
<input type="button" class="addYourCSSClassHere" value="WordsOnButton" onclick="window.location= '@Url.Action( "ActionInControllerHere", "ControllerNameHere")'" />
DenaliHardtail
Updated on July 17, 2022Comments
-
DenaliHardtail almost 2 years
I have a view with a button. When the user clicks the button I want them redirected to a data entry view. How do I accomplish this? I should mention the views are created, tested, and functioning. I can get to them by typing the url.
I looked for steps explaining how to wire up the onclick event of the button but I'm new to MVC and kinda lost at this point.
Thanks!
-
DenaliHardtail almost 14 yearsThis is an <input type="button" />
-
phougatv almost 9 years
@Html.TextBox("btnAdd", "Add New", new { type = "button" }
, is it possible to addaction
and/orcontroller
to this razor code so that on clicking this particular button I get redirected to anotheraction
in the same/different controller? -
Sribin about 6 yearsHow to pass parameter in this .Please help
-
AGuyCalledGerald over 3 years'@Url.Action("actionName", "controllerName", new { myparam = "blabla" })'