ekk*_*kis 4 c# overloading ambiguity asp.net-mvc-3
我有一个控制器,有3个重载的create方法:
public ActionResult Create() {}
public ActionResult Create(string Skill, int ProductId) {}
public ActionResult Create(Skill Skill, Component Comp) {}
Run Code Online (Sandbox Code Playgroud)
在我的一个观点中,我想创建这个东西,所以我称之为:
<div id="X">
@Html.Action("Create")
</div>
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
{"控制器类型'XController'上的当前操作请求'Create'在以下操作方法之间是不明确的:System.Web.Mvc.ActionResult类型X.Web.Controllers.XController上的Create()System.Web.Mvc.ActionResult在类型X.Web.Controllers.XController上创建(System.String,Int32)System.Web.Mvc.ActionResult在类型X.Web.Controllers上创建(X.Web.Models.Skill,X.Web.Models.Component). XController"}
但由于@html.Action()没有传递任何参数,因此应该使用第一个重载.它对我来说似乎不明确(这只意味着我不认为像ac#编译器).
任何人都可以指出我的方式错误吗?
默认情况下,ASP.NET MVC不支持重载方法.您必须使用差异操作或可选参数.例如:
public ActionResult Create() {}
public ActionResult Create(string Skill, int ProductId) {}
public ActionResult Create(Skill Skill, Component Comp) {}
Run Code Online (Sandbox Code Playgroud)
将改为:
// [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
}
Run Code Online (Sandbox Code Playgroud)
要么:
// [HttpGet] by default
public ActionResult Create() {}
[HttpPost]
public ActionResult Create(string Skill, int ProductId) {}
[HttpPost]
public ActionResult CreateAnother(Skill Skill, Component Comp) {}
Run Code Online (Sandbox Code Playgroud)
要么:
public ActionResult Create() {}
[ActionName("CreateById")]
public ActionResult Create(string Skill, int ProductId) {}
[ActionName("CreateByObj")]
public ActionResult Create(Skill Skill, Component Comp) {}
Run Code Online (Sandbox Code Playgroud)