c# - 解决歧义

标签 c# asp.net-mvc-3 overloading ambiguity

我有一个 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) {}

See also this Q&A

关于c# - 解决歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7831896/

相关文章:

c# - 如何过滤 AutoCompleteBox 中第一个匹配项的项目列表?

c# - 通过路径名返回 View

asp.net-mvc-3 - MVC 3 - route 的斜线和空格

c# - 从强类型 Razor View 使用 Html.BeginForm 传递值

C++ 重载运算符 [ ][ ]

类型脚本方法重载不同类型的参数但相同的响应

java - 重载的精度高于覆盖

c# - 为什么我不能两次更改 bool 值?

c# - Lumesse Web 服务和 WSSE 纯文本安全问题

c# - 如何使 TreeView 背景色透明?