my problem is that I want to add a button from this template: https://designreset.com/cork-admin-v1/ltr/demo3/element_buttons.html
If I click on a button I want to run a function at my controller, how can I do this? Already tried it with code like that:
<button type="button" onclick='[email protected]("redirect","Login")'" class="btn btn-info mb-2">Info</button>
This is not working. I also tried it with javascript, this works but I don't think that that is the best way.
<span onclick="login()" class="btn btn-primary" value="">Log In</span>"
<script>
function login() {
let userName = $('.userName').val();
let password = $('.password').val();
$.ajax({
url: '/login/login?userName=' + userName + '&&password=' + password,
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log(data);
alert(data);
window.location.href = "/login/home";
},
error: function (resp) {
alert(resp);
console.log(resp);
}
});
}
</script>
Could someone say me if I need to do this really with javascript? Or can I directly call the controller action, when yes, how?
EDIT:
With the following code it seems to work:
<button type="submit" asp-action="redirect" class="btn btn-info mb-2">Info</button>
Try this instead for ASP.NET MVC 5:
<button type="button" onclick="window.location='@Url.Action("ActionName", "ControllerName")'" class="btn btn-info mb-2">Info</button>
For ASP.NET Core, your code is correct,
<button type="submit" asp-action="redirect" asp-controller="ControllerNameHere" class="btn btn-info mb-2">Info</button>
Additional details can be also specified like passing values on the Controller:
<button type="submit" asp-action="redirect" asp-controller="ControllerNameHere" asp-route-AnyId="@Model.AnyId" class="btn btn-info mb-2">Info</button>