Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have duplicate action names and parameter list for post and get?

is it possible to have 2 actions with the same name and parameters but one's a post, the other a get? e.g Delete(id) and [HttpPost]Delete(id)...i get an error saying that this is not allowed...

like image 371
newbie_86 Avatar asked Jun 01 '11 08:06

newbie_86


People also ask

Can we have two action methods with same name in MVC?

While ASP.NET MVC will allow you to have two actions with the same name, . NET won't allow you to have two methods with the same signature - i.e. the same name and parameters. You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.

Can two different controllers have action methods with the same name?

This will fail when you will call these because the MVC framework won't know which one to call. You have two solutions to make MVC routing know which action to use. First, you can change the name.

How is action method link to the view?

ActionLink() does not link to a view. It creates a link to a controller action. The first parameter is the link text, and the second parameter is the name of the controller action.


2 Answers

Yes, it's possible. Just use ActionName attribute on one action:

        public ActionResult Delete(int id)
        {
            //...
            return View();
        }

        [HttpPost]
        [ActionName("Delete")]
        public ActionResult Delete_Post(int id)
        {
            //...
            return View();
        }
like image 101
frennky Avatar answered Oct 17 '22 12:10

frennky


The reason you get the error that it is not allowed is because C# itself gets confused. While in MVC you can add attributes to specify whether a function is HttpGet or HttpPost, that doesn't help C# determine the difference between one or the other. In order to have 2 functions with exactly the same name, the parameter list needs to be different.

As frennky pointed out, the ActionName attribute works in MVC because MVC uses aliases as part of the process for determining which action to call (along with attributes, but not parameters).

As a side note, it's probably best not to have a Delete action on a GET request. You don't want a crawler or some other bot accidently hitting the wrong link :P

like image 32
Daniel Young Avatar answered Oct 17 '22 13:10

Daniel Young