问题描述
我有3重载控制器的创建方法:
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:
{行动创建当前请求的控制器类型
'XController'不明确下面的操作方法之间:
System.Web.Mvc.ActionResult的Create()上类型
X.Web.Controllers.XController System.Web.Mvc.ActionResult
型上X.Web.Controllers.XController
System.Web.Mvc创建(System.String,的Int32)。的ActionResult创建(X.Web.Models.Skill,
X.Web.Models.Component)的类型X.Web.Controllers.XController}
但由于 @ html.Action()
被传递任何参数,应使用第一个重载。它似乎并不含糊,我(这只是意味着我不认为像C#编译器)。
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?
推荐答案
默认情况下,重载方法在ASP.NET MVC中不被支持。你必须使用不同的行动或可选参数。例如:
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) {}
将变为:
// [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) {}
的
这篇关于解决歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!