1

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.

4
  • You mean the code Debug.Write is not executing? Did you try to debug? Do you have a view with name PostTest ? Commented Oct 23, 2020 at 1:15
  • @ChetanRanpariya correct, the output never arrives in the console. And no I have no view with that name, just the function. Do I need a view for every function ? Commented Oct 23, 2020 at 1:17
  • 1
    I think I can see the real issue now.. Html.BeginForm("PostTest", "Index" should haveSmoothies instead of Index. And yes, since you're are doing return View() it will try to load view with the same name as controller action. So you need to have view with the same name as action name. Or you can return some tiger view by specifying name in View(). Example return View("some view"); Commented Oct 23, 2020 at 1:21
  • @ChetanRanpariya Ah Yes! Now it's getting somewhere. Thank you for the assistance it's a good bit clearer now. I think I can finish it from here. Commented Oct 23, 2020 at 1:25

2 Answers 2

1

Your url is wrong. It should be

@using (Html.BeginForm("PostTest", "Smoothies", FormMethod.Post))
{
    <input type="submit" name="submit" value="Test" />
}
Sign up to request clarification or add additional context in comments.

Comments

0

Please check your URL, It seems wrong.

Your URL will be "ControllerName/Methodname".

in your case it will "Smothies/PostTest"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.