MVC中的重载视图?

时间:2013-03-12 09:27:54

标签: asp.net-mvc

我希望链接http://localhost:2409/Account/Confirmation/16和链接http://localhost:2409/Account/Confirmation/(不带参数)。
但是使用此操作方法,它无效。为什么呢?

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

        return View();
    }

第二,我只想返回View,如果parametr为空。

    public ActionResult Confirmation()
    {

        return View();
    }

错误(已翻译):

  

控制器确认的当前操作请求   AccountController在以下方法之间是不明确的   action:System.Web.Mvc.ActionResult Confirmation(Int32,   System.String)用于TC.Controllers.AccountController类型   System.Web.Mvc.ActionResult类型的确认()   TC.Controllers.AccountController

2 个答案:

答案 0 :(得分: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 } 
);

答案 1 :(得分:0)

没有必要为它制作2种方法。您的HTTP请求混淆了在两种情况下都应该调用ActionMethod;

http://localhost:2409/Account/Confirmation/16 
http://localhost:2409/Account/Confirmation/

而不是所有这些,只需创建一个方法。使其参数可选或为参数指定一些默认值。以下是2个例子来理解它。

// 1. Default value to paramter
public ActionResult Confirmation(int id = 0, string hash = null)
{
    //Some code..

    return View();
}  

// 2. Make id optional
public ActionResult Confirmation(int? id, string hash)
{
    //Some code..

    return View();
} 

您可以采用任何一种方法。

相关问题