2011-10-20 92 views
4

我有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#編譯器)。

任何人都可以指出我的方式的錯誤?

回答

7

默認情況下,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 
} 

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

+0

是的,我看到......感謝您的認真回覆。你得到一個點:) – ekkis

+0

歡迎您:D ans謝謝接受答案 –

+0

恥辱鏈接的問題被刪除。 7536119/mvc3-routing-with-overloaded-query-parameters – Maggie

1

您可以使用ActionName屬性爲所有3種方法指定不同的操作名稱

+0

感謝Ankur,你明白了:) – ekkis