Ondra Netočný
Ondra Netočný

Reputation: 410

Overload action with different parameters

I have several model classes inherited from common base (e.g. Class1, Class2 inherits from CommonClass). I would like to write separate overloaded controller action which would have each of these model classes as parameter. For example:

    [HttpPost]
    public JsonResult MyAction(Class1 data)
    {
       // handle data here
    }

    [HttpPost]
    public JsonResult MyAction(Class2 data)
    {
       // handle data here
    }

Is it somehow possible to achieve that? When I try to simply write those action methods, MVC throws System.Reflection.AmbiguousMatchException.

I have also tried to write single action with base class as parameter and then cast data to specific class, but this gives me null.

    [HttpPost]
    public JsonResult MyAction(CommonClass data)
    {
        if(data.IsSomething)
        {
            var castedData = data as Class1;
            // process casted data
        }
        else
        {
            var castedData = data as Class2;
            // process casted data
        }
    }

Upvotes: 2

Views: 1490

Answers (2)

Pedro Benevides
Pedro Benevides

Reputation: 1974

You could decorate your action with the [ActionName] annotation. Like this:

[HttpPost, ActionName("OtherName")]
public JsonResult MyAction(Class1 data)
{
   // handle data here
}

[HttpPost]
public JsonResult MyAction(Class2 data)
{
   // handle data here
}

And with that you can use to put names with characters that .NET do not allow, like [ActionName("This-Example")]

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039408

You cannot have multiple actions with the same name and HTTP verb on the same controller. You will need to have different action names and routes.

Alternatively you may checkout this answer in which I illustrate how you could write a custom model binder and achieve polymorphic binding (your second attempt with the base class).

Upvotes: 4

Related Questions