Overload action method but different route template(with controller name and without controller name) in .net core 5 MVC

702 Views Asked by At

I have 2 action method and 1 view. I want send post request but with controller name after submit on the view. But open page without controller name.

Controller

public class ProductController : Controller
    {
        [HttpGet("/CreateProduct")]
        public IActionResult CreateProduct()
        {
            Product product = new Product()
            {
                Price = new Price()
            };
            return View(product);
        }
        [HttpPost()]
        public IActionResult CreateProduct(Product product)
        {
            return View();
        }
    }

and Actoin

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@model MvcDemo.Models.Product

<form asp-controller="Product" asp-action="CreateProduct" method="post">
    <input type="text" asp-for="Name" placeholder="Product Name"/> <br/>
    <input type="number" asp-for="Quantity" placeholder="Quantity"/> <br/>
    <input type="number" asp-for="Price.SimplePrice" placeholder="Price"/> <br/>
    <input type="number" asp-for="Price.DiscountPrice" placeholder="Discount Price"/> <br/>


    <input type="submit"/>
</form>

I want to open Page host/CreateProduct but send post request host/product/CreateProduct after submit.

But not working.

Http Error 405. This page isn’t working

Submit button send post request host/CreateProduct. I know the solution to the problem [HttpPost("/CreateProduct")].

But I'm interested in why it doesn't work.

Startup route configuration

app.UseEndpoints(endpoint =>
            {
                endpoint.MapDefaultControllerRoute();
            });
1

There are 1 best solutions below

4
On

when attribute routing starts from "/" it means that the route starts from root. If you want to start from controller

        [HttpPost("/product/CreateProduct")]
        public IActionResult CreateProduct()

or add attribute to the controller

 [Route("[controller]/[action]")]
public class ProductController : Controller

if you want everything working the way you want , you have to map controller route this way . In this case you will not need an attribute routing at all

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

            });