0

As the heading states when I click a button on my main view I need it to call a method in my controller for that view. Ive been trying for hours and Ive changed the specific lines of code many times but all variations seem to give the same errors so im just showing the simplest versions to get my point across. Everytime I try something I get a 404 error that the path is not found. So im assuming something is wrong with the code in my view. Im not using JQuery or any javascipt

The line of code in my index view:

@Html.ActionLink("Button4Pressed", "Button4Pressed", "HomeController");

I know this wont work for getting methods but it works for changing pages so I thought I would start there. Im not sure if I should be doing it as a href or button.

my method in my HomeController:

 [HttpPost]
    public ActionResult Button4Pressed()
    {
        state = "year";
        MyChart();
        return View();
    }

heres my Solution Explorer

Im pretty new to MVC and propably doing some pretty stupid stuff so any help is appreciated thanks.

  • 1
    The 3rd parameter is `"Home"`, not `"HomeController"` (unless you have a controller named `HomeControllerController`) –  Sep 23 '18 at 08:57
  • 1
    On top of that, `ActionLink` makes a `GET` link, you have a `POST` method in the controller. – GSerg Sep 23 '18 at 08:59
  • I did try that a while ago but thanks for just confirming. unfortunately I still get the 404 error. I dont know if it should be just action or if it should be @Url rather. I think this is the part im messing up. – Joshua Weiss Sep 23 '18 at 08:59
  • 1
    Possible duplicate of [ASP.NET MVC ActionLink and post method](https://stackoverflow.com/questions/2048778/asp-net-mvc-actionlink-and-post-method) – GSerg Sep 23 '18 at 09:04
  • That link is exactly what im trying to do but im not using JQuery – Joshua Weiss Sep 23 '18 at 09:07
  • @JoshuaWeiss It's either javascript (not necessarily jQuery) or a `submit` button in an HTML form. – GSerg Sep 23 '18 at 09:12

1 Answers1

0

You have two options:

Option A

Remove the [HttpPost] attribute from your controller method and you will be able to create normal links to it, i.e. with @Html.ActionLink()

Option B

Keep the [HttpPost] attribute and use a form or ajax to send the request as a HTTP Post request, i.e.

<form id="Button4Pressed" action="@Url.Action("Button4Pressed", "Home")" method="post"></form>
<a href="#" onclick="javascript:document.getElementById('Button4Pressed').submit()">Button4</a>
Saeed Prez
  • 728
  • 3
  • 8