2013-03-12 48 views
2

我想要链接http://localhost:2409/Account/Confirmation/16和那个链接http://localhost:2409/Account/Confirmation/(不带参数)。
但是用这个动作方法,它不起作用。为什么?MVC中的重载视图?

public ActionResult Confirmation(int id, string hash) 
    { 
     Some code.. 

     return View(); 
    } 

秒,我只是想返回查看,如果parametr是空的。

public ActionResult Confirmation() 
    { 

     return View(); 
    } 

错误(翻译):

用于在控制器的确认动作的当前请求 的AccountController是 动作的下列方法之间暧昧:System.Web.Mvc.ActionResult确认(的Int32, System.String)for TC.Controllers.AccountController System.Web.Mvc.ActionResult Confirmation()for type TC.Controllers.AccountController

回答

4

使用相同的HTTP动词不能有多个具有相同名称的动作(在您的情况下为GET)。您可以以不同方式命名动作,但这意味着链接将更改,或者您可以使用不同的VERB,但也可能导致其他像你这样的问题不能只是在浏览器中输入链接。

你应该做的是改变你的id是可选的int?和合并的两个动作为一:

public ActionResult Confirmation(int? id, string hash) 
{ 
    if(id.HasValue) 
    { 
     //Some code.. using id.Value 

     return View(); 
    } 

    //There was no Id given 
    return View(); 
} 

您可能还需要允许你的路线,该id是可选的。如果你使用默认路由,这应该是默认设置:

routes.MapRoute(
    "Default", // Route name 
    "{controller}/{action}/{id}", // URL with parameters 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
); 
+0

我想出了'int?'的相同想法!无论如何感谢,当然还有+1 :) – whoah 2013-03-12 09:42:44