0

I have developed an HTML form wizard that helps creating an object compose the data to send to the server.

I have a controller with two action methods as follow:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveItem( TypeOneItem model, int customerID ) {

and

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveItem( TypeTwoItem model, int customerID ) {

TypeOneItem and TypeTwoItem are both subclass of BaseItem. The class are defined this way

public class BaseItem 
{
    public int ItemID { get; set; }
    public string Name { get; set; }
}

public class TypeOneItem : BaseItem
{
    public int Property1 { get; set; }
    public string Property2 { get; set; }
}

public class TypeTwoItem : BaseItem
{
    public string Property3 { get; set; }
    public int Property4 { get; set; }
    public double Property5 { get; set; }
}

However, even if I am posting the right data to be binded to just one of the two concrete classes I get the error "The current request for action 'SaveItem' on controller type 'ManageController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult SaveItem(TypeOneItem, Int32) System.Web.Mvc.ActionResult SaveItem(TypeTwoItem, Int32)"

Why does this happens? I do not want to change the server action name and hard code the difference on the UI wizard. Is there another way to solve this problem?

Lorenzo
  • 29,081
  • 49
  • 125
  • 222
  • You can implement a custom model binder – Vsevolod Goloviznin Jan 16 '15 at 14:24
  • 4
    MVC cannot distinguish between functions solely based on parameter names/types, giving you two ActionMethods with the same function name, thus the ambiguous error message. It doesn't know which one you want. Either you need to change one of your ActionMethod names or tinker with AttributeRouting - though I have never messed with this and not 100% that it will do what you want - http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx. – Tommy Jan 16 '15 at 14:28
  • What about the [Bind](http://msdn.microsoft.com/en-us/library/system.web.mvc.bindattribute%28v=vs.118%29.aspx) attribute including all the parameters and so excluding one model from the other? – Lorenzo Jan 16 '15 at 14:39
  • @VsevolodGoloviznin: Could you please further elaborate a quick sample? – Lorenzo Jan 16 '15 at 14:47
  • Also you can write an ActionSelector that will select the right overload based on the form parameters. – AgentFire Jan 16 '15 at 19:23
  • @AgentFire: Any example? – Lorenzo Jan 16 '15 at 19:47
  • @Lorenzo http://www.codeproject.com/Articles/291433/Custom-Action-Method-Selector-in-MVC – AgentFire Jan 17 '15 at 07:42

1 Answers1

1

MVC supports method overloading based on attributes but it wont do it solely based on different method signatures. You can look at for reference ASP.NET MVC ambiguous action methods

Community
  • 1
  • 1
Lav
  • 1,850
  • 15
  • 17