Search code examples
c#http-postasp.net-core-mvcasp.net-mvc-routing

.net core not routing to POST method


Link to project here -> https://github.com/crumdev/hqbbq.git

I have a simple 3 page MVC website with 1 controller. For the contact page I have a small 3 input form. Below are the Controller methods:

[Route("contact/")]
public IActionResult Contact()
{
    return View();
}

[HttpPost]
public IActionResult Contact(string name, string email, string message)
{
    ViewBag.Name = name;
    ViewBag.Email = email;
    ViewBag.Message = message;

    return View();
}

When I submit the form with a breakpoint inside of the Contact method for HttpPost it never breaks but instead uses the regular method and just returns the view again. I have tried reducing my form to just the name field and only capture that and it does not enter the POST method. I have given the regular Contact method the [HttpGet] attribute so it can only be used strictly for GET requests and when I submit the form then it bypasses my controller altogether and returns the Dev exception page that is blank except for "Hello World!" on the screen. I have read through the documentation and followed tutorials on teamtreehouse.com for regular ASP.Net as well but cannot understand why it is behaving this way.

Edit: Here is the code for the page submitting the POST. I am just using a plain HTML form with the POST method for submitting the data.

https://github.com/crumdev/hqbbq/blob/master/HQ-BBQ/Views/Home/contact.cshtml


Solution

  • The POST action needs to have a route as well if the intention is to use attribute routing.

    [HttpGet]
    [Route("contact")]
    public IActionResult Contact() {
        return View();
    }
    
    [HttpPost]
    [Route("contact")]    
    public IActionResult Contact(string name, string email, string message) {
        ViewBag.Name = name;
        ViewBag.Email = email;
        ViewBag.Message = message;
    
        return View();
    }
    

    Note the exclusion of the slashes as they are not needed. Make sure the names and ids of the form inputs match the parameters of the target action