【问题标题】:overload views in MVC?MVC 中的重载视图?
【发布时间】:2013-03-12 09:27:54
【问题描述】:

我想要链接http://localhost:2409/Account/Confirmation/16 和链接http://localhost:2409/Account/Confirmation/(不带参数)。
但是使用这种操作方法,它不起作用。为什么?

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

        return View();
    }

其次,如果参数为空,我只想返回视图。

    public ActionResult Confirmation()
    {

        return View();
    }

错误(翻译):

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

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

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

    您应该做的是将您的 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 } 
    );
    

    【讨论】:

    • 我想出了与int? 相同的想法!无论如何谢谢,当然+1 :)
    【解决方案2】:

    没有必要为它制作 2-methods。您的 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();
    } 
    

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

    【讨论】:

      猜你喜欢
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多