简体   繁体   中英

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

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:功能

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,

按钮

but when I press it...

按钮

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.

Your url is wrong. It should be

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

Please check your URL, It seems wrong.

Your URL will be "ControllerName/Methodname".

in your case it will "Smothies/PostTest"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM