Home > Net >  ASP.NET MVC : Actionlink does not navigate to correct action method of same name but different param
ASP.NET MVC : Actionlink does not navigate to correct action method of same name but different param

Time:12-28

I have two action methods with same name. And they both are decorated with the Http verbs 'Get' and 'Post', and also their parameter list is different.

 [HttpGet]
 public ActionResult Transaction()

 [HttpGet]
 public ActionResult Transaction(int recordId)

 @Html.ActionLink("Back to Main page", "Transaction", new { recordId= Model.studentId })

Both are named Transaction, one takes a parameter while the other does not take any.

The action link intended to call the Transactions(int recordId) method when that button hit, always navigates to Transaction() but not to Transaction(int recordId).

I have two questions:

  1. Why is my code always reaching the method which doesn't have a parameter, even though the action link has a parameter?

  2. I have decorated my action methods with HttpPost and HttpGet, how I can include the HttpGet or HttpPost with the action link or with any other form element?

CodePudding user response:

An ActionLink is rendered as an <a href="...."> HTML element and therefore is always a GET request and thus always goes to the action method decorated with [HttpGet] annotation - it does NOT look at any parameter list or anything like that.

If you want to call the POST action method, you need to have a HTML form and a submit button on that form - that will be a POST request to be handled by the method decorated with the [HttpPost] annotation ...

  • Related