Home > OS >  Returning a method for a form
Returning a method for a form

Time:03-13

I have a form which after clicking Submit should call the AddProduct method

View

@using (Html.BeginForm("AddProduct", "Home", FormMethod.Post))

The problem is the controller. Has a specified Route.

In this situation, when I click Submit, AddProduct is not called, but Index

HomeController

[Route("{name?}/{adminCode?}")]
public IActionResult Index(string name, string adminCode)

[HttpPost]
public ActionResult AddProduct(string productName)

How to call the AddProduct method correctly?

CodePudding user response:

Because of the optional route parameters and the lack of a HTTP Verb on the Index action you most are most likely encountering a route conflict.

First option would be to use the appropriate route attribute on the action.

[Route("[controller]")]
public HomeController {

    [HttpGet("{name?}/{adminCode?}")]
    public IActionResult Index(string name, string adminCode) {
        //...
    }

    [HttpPost]
    public ActionResult AddProduct(string productName) {
        //...
    }
    
}

That way when the post is made it will only consider actions that can handle POST requests.

Another option I would suggest is moving AddProduct to a separate controller (like ProductController).

HomeController

[Route("[controller]")]
public HomeController {

    [HttpGet("{name?}/{adminCode?}")]
    public IActionResult Index(string name, string adminCode) {
        //...
    }
    
}

ProductController

[Route("[controller]")]
ProductController {

    [HttpPost]
    public ActionResult AddProduct(string productName) {
        //...
    }
}

and updating the view accordingly

@using (Html.BeginForm("AddProduct", "Product", FormMethod.Post))

Apart from that, there is not enough details about what you are actually trying to achieve here, so I would also suggest adding more details about the main goals so that a more target answer can be provided.

CodePudding user response:

Because of a wrong route config, controller can't see you that you have AddProduct action, and uses default Index action with AddProduct as a name parameter. So try to add a route to AddProduct too

[Route("~/Home/AddProduct")]
public ActionResult AddProduct(string productName)

if the problem continues with another actions. Pls post your controller header and config routes code. Probably it needs to be fixed.

  • Related