Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net-core-mvc c#

Call a simple function from a button in ASP.NET Core (MVC)

发布于 2021-02-19 12:47:04

I've been looking really hard to answer what I thought would be such a simple question, but how do I call a function from the Controller of a page using an HTML form/button.

The end-goal here is to make an add-to-cart button, but I must firstly figure out how to make a button in the first place.


This is the most common method I saw people doing:

The function in my controller I want to run is as such: Function

and then in my Index.cshtml file I have this block of code:

@using (Html.BeginForm("PostTest", "Index", FormMethod.Post))
{
    <input type="submit" name="submit" value="Test" />
}

and the button shows up as it should,

Button

but when I press it...

Button

It just redirects to a page with the name of the function i'm trying to call instead of actually running it. I clearly have a fundamental misunderstanding of how the buttons work, but this is the answer I keep finding online.

Questioner
Sam Tubb
Viewed
0
788 2020-10-24 07:37

Your url is wrong. It should be

@using (Html.BeginForm("PostTest", "Smoothies", FormMethod.Post))
{
    <input type="submit" name="submit" value="Test" />
}