【问题标题】:Ambiguous in Actions in asp.net mvc, how to resolve it?asp.net mvc中的Actions模棱两可,如何解决?
【发布时间】:2012-10-11 14:06:57
【问题描述】:

我有两种方法:

public ActionResult Index(int? id)
{
    return Redirect("/View/" + this.GetMenuItems().First().Id);
}

public ActionResult Index(int id, uint? limit)
{

当我转到 /View/1 - 我得到那个错误

当前对控制器类型“ViewController”的操作“Index”的请求在以下操作方法之间不明确: SVNViewer.Controllers.ViewController 类型上的 System.Web.Mvc.ActionResult Index(System.Nullable1[System.Int32]) on type SVNViewer.Controllers.ViewController System.Web.Mvc.ActionResult Index(Int32, System.Nullable1[System.UInt32])

我需要这两种方法,但要消除歧义错误,我该怎么做?

【问题讨论】:

  • 将其中一种方法重命名为其他方法:索引的第二种方法 -> MenuItem 也许?或者,在第二个中将限制参数设为必需(不可为空)。
  • @Tommy 如果你回答这个问题,我会投票的
  • @Mark - 我很感激,但是当我遇到这个问题时,我没有足够的时间来制定一个好的答案,但我想为 testCoder 投入 2 美分!

标签: c# asp.net .net asp.net-mvc


【解决方案1】:

将您的第二个 Action 更改为不具有可为空的 uint。

public ActionResult Index(int id, uint limit)

你的Index(int? id)应该是在limit为null时处理的方法。

【讨论】:

    【解决方案2】:

    您可以使用 ActionName 解决此问题:Purpose of ActionName

    如果两者都做同样的事情,你可以这样做:

    public ActionResult Index(int? id, uint? limit = null)
    {
      ...
    }
    

    使第二个参数可选。

    或者有一个有 [HttpGet] 属性,一个有 [HttpPost],如果一个响应 get 而另一个响应发布的表单。

    【讨论】:

      【解决方案3】:

      您可以创建一个模型并且只有一个操作方法:

      public class MyActionModel 
      {
          public int? Id { get;set; }
          public int? Limit { get;set; }
      }
      

      然后在你的控制器中:

      public ActionResult Index(MyActionModel model)
      {
          // Your code here
          if (model.Id.HasValue() { // do something....etc}
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-11
        • 2017-10-25
        • 1970-01-01
        • 2012-12-08
        • 2013-05-13
        相关资源
        最近更新 更多