开发者

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 tha开发者_如何学编程t this is not allowed...


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();
        }


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜