Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these two Actions considered ambiguous despite the parameters being different?

The current request for action 'Index' on controller type 'UsersController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult PostUser(Models.SimpleUser) on type Controllers.UsersController System.Web.Mvc.ActionResult PostUser(Int32, Models.SimpleUser) on type Controllers.UsersController

Is happening when I try to POST website.com/users/ with form values.

When there is NO ID (website.com/users/) I want it to create a new user, when there IS an ID (/users/51 for example) I want it to update that user, so how can I make it tell the difference between these two Actions?

Here are the two actions:

    [HttpPost]
    [ActionName("Index")]
    public ActionResult PostUser(SimpleUser u)
    {

        return Content("User to be created...");
    }

    [HttpPost]
    [ActionName("Index")]
    public ActionResult PostUser(int id, SimpleUser u)
    {

        return Content("User to be updated...");
    }

Here is the MapRoute:

    routes.MapRoute(
        "Users",
        "users/{id}",
        new { controller = "Users", action = "Index" }
    );
like image 353
MetaGuru Avatar asked Jul 13 '11 14:07

MetaGuru


1 Answers

The main problem is there is some ambiguity between your two action methods, as model binding doesn't help decern the routing configuration. Your current routing simply points to index method.

You can still have the same URL, but it would be helpful to name your actions differently and then apply some new routes.

[HttpPost]
public ActionResult Create(SimpleUser u)
{
    return Content("User to be created...");
}

[HttpPost]
public ActionResult Edit(int id, SimpleUser u)
{
    return Content("User to be updated...");
}

And then in your routing try

routes.MapRoute(
    "UserEdit",
    "users/{id}",
    new { controller = "Users", action = "Edit", 
        httpMethod = new HttpMethodConstraint("POST") });

routes.MapRoute(
    "UserCreate",
    "users",
    new { controller = "Users", action = "Create", 
        httpMethod = new HttpMethodConstraint("POST") });

The routes will be constrained to POST events only, which means you can still add some routing for your GET methods on the same route. Such as for a list or something.

like image 102
Daniel Young Avatar answered Nov 11 '22 22:11

Daniel Young