Search code examples
.netasp.net-corerazorhttp-post

I'm getting an error that Page is not working with HttpPost


I'm not getting what's going on:

In my HomeController I have a:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public IActionResult Post()
    {
        return View(new Post());
    }

    [HttpPost]
    public IActionResult Edit(Post post)
    {
        return View();
    }
}

If I run my app and go to localhost8888/Home/Edit I get a 405 error with `

This Page is not working

However if I change EDIT method to [HttpGet] or remove the action all together the Edit razor view loads successfully.

Razor View:

@model Post


<div>
<form asp-controller="Home" asp-action="Edit" method="post">
    <div>
        <label>Title</label>
        <input asp-for="@Model.Title"/>

        <label>Body</label>
        <input asp-for="@Model.Body" />
    </div>
    <input type="submit" value="Submit"/>
</form>
</div>

Why is that happening?


Solution

  • When you navigate to /Home/Edit the browser makes a GET request to your server. So to handle this request you need an [HttpGet] method in your controller.

    When you submit the form the browser sends a POST request to the server. So to handle this request you need an [HttpPost] method in your controller.

    So basically you need two Edit methods one for handling the first scenario and one for the second.

    public class HomeController : Controller
    {
        ...
        ...
    
        // handles the GET when user navigates to /Home/Edit and returns the Edit View
        [HttpGet]
        public IActionResult Edit()
        {
            return View();
        }
    
        // handles the POST request when user submits the form and processes the user input
        [HttpPost]
        public IActionResult Edit(Post post)
        {
            if (!ModelState.IsValid)
            {
                // form input was not valid
                // return back to Edit view to show the validation errors
                return View(post);
            }
            
            // form input is valid
            // process the data, probably save to database
    
            // the post was edited successfully, redirect to Index View
            return RedirectToAction("Index");
        }
    }