我有一个 Controller ,其中有 3 个用于创建方法的重载:
public ActionResult Create() {}
public ActionResult Create(string Skill, int ProductId) {}
public ActionResult Create(Skill Skill, Component Comp) {}
在我的一个观点中,我想创建这个东西,所以我这样调用它:
<div id="X">
@Html.Action("Create")
</div>
但是我得到了错误:
{"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"}
但由于 @html.Action()
没有传递任何参数,所以应该使用第一个重载。这对我来说似乎没有歧义(这只意味着我不像 c# 编译器那样思考)。
谁能指出我方法的错误?
最佳答案
默认情况下,ASP.NET MVC 不支持重载方法。您必须使用不同的操作或可选参数。例如:
public ActionResult Create() {}
public ActionResult Create(string Skill, int ProductId) {}
public ActionResult Create(Skill Skill, Component Comp) {}
将更改为:
// [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
}
或者:
// [HttpGet] by default
public ActionResult Create() {}
[HttpPost]
public ActionResult Create(string Skill, int ProductId) {}
[HttpPost]
public ActionResult CreateAnother(Skill Skill, Component Comp) {}
或者:
public ActionResult Create() {}
[ActionName("CreateById")]
public ActionResult Create(string Skill, int ProductId) {}
[ActionName("CreateByObj")]
public ActionResult Create(Skill Skill, Component Comp) {}
关于c# - 解决歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7831896/