Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving ambiguity

I have a controller with 3 overloads for a create method:

public ActionResult Create() {}
public ActionResult Create(string Skill, int ProductId) {}
public ActionResult Create(Skill Skill, Component Comp) {}

in one of my views I want to create this thing so I call it like this:

<div id="X">
@Html.Action("Create")
</div>

but I get the error:

{"The current request for action 'Create' on controller type 'XController' is ambiguous between the following action methods: System.Web.Mvc.ActionResult Create() on type X.Web.Controllers.XController System.Web.Mvc.ActionResult Create(System.String, Int32) on type X.Web.Controllers.XController System.Web.Mvc.ActionResult Create(X.Web.Models.Skill, X.Web.Models.Component) on type X.Web.Controllers.XController"}

but since the @html.Action() is passing no parameters, the first overload should be used. It doesn't seem ambiguous to me (which only means I don't think like a c# compiler).

can anyone point out the error of my ways?

like image 518
ekkis Avatar asked Feb 22 '23 15:02

ekkis


1 Answers

By default, overloading methods is not supported in ASP.NET MVC. You have to use difference actions or optional parameters. For example:

public ActionResult Create() {}
public ActionResult Create(string Skill, int ProductId) {}
public ActionResult Create(Skill Skill, Component Comp) {}

will changes to:

// [HttpGet] by default
public ActionResult Create() {}

[HttpPost]
public ActionResult Create(Skill skill, Component comp, string strSkill, int? productId) {
    if(skill == null && comp == null 
        && !string.IsNullOrWhiteSpace(strSkill) && productId.HasValue)
        // do something...
    else if(skill != null && comp != null
        && string.IsNullOrWhiteSpace(strSkill) && !productId.HasValue)
        // do something else
    else
        // do the default action
}

OR:

// [HttpGet] by default
public ActionResult Create() {}

[HttpPost]
public ActionResult Create(string Skill, int ProductId) {}

[HttpPost]
public ActionResult CreateAnother(Skill Skill, Component Comp) {}

OR:

public ActionResult Create() {}
[ActionName("CreateById")]
public ActionResult Create(string Skill, int ProductId) {}
[ActionName("CreateByObj")]
public ActionResult Create(Skill Skill, Component Comp) {}

See also this Q&A

like image 100
amiry jd Avatar answered Mar 08 '23 09:03

amiry jd