【问题标题】:How define action in the case of different parameters? - asp.net mvc4在不同参数的情况下如何定义动作? -asp.net mvc4
【发布时间】:2012-09-09 13:47:46
【问题描述】:

我尝试为差异参数定义操作,但它不起作用:

public class HomeController : Controller
  {
    public ActionResult Index()
    {
      return  View();
    }

    public ActionResult Index(string name)
    {
      return new JsonResult();
    }

    public ActionResult Index(string lastname)
    {
      return new JsonResult();
    }

    public ActionResult Index(string name, string lastname)
    {
      return new JsonResult();
    }
    public ActionResult Index(string id)
    {
      return new JsonResult();
    }
 }

但我得到错误:

当前对控制器类型“HomeController”的操作“Index”的请求在以下操作方法之间不明确......

编辑:

如果不可能,请提出最好的方法。

谢谢,

约瑟夫

【问题讨论】:

    标签: asp.net asp.net-mvc-4


    【解决方案1】:

    您可以使用ActionNameAttribute 属性:

    [ActionName("ActionName")]
    

    然后,每个 Action 方法都有不同的名称。

    【讨论】:

    • 谢谢,你能为我写的案例举一些例子吗?
    【解决方案2】:

    当它们响应相同类型的请求(GET、POST 等)时,您不能重载操作方法。您应该有一个包含所有您需要的参数的公共方法。如果请求没有提供它们,它们将为空,您可以决定可以使用哪个重载。

    对于这个单一的公共方法,您可以通过定义模型来利用默认模型绑定。

    public class IndexModel
    {
        public string Id { get; set;}
        public string Name { get; set;}
        public string LastName { get; set;}
    }
    

    你的控制器应该是这样的:

    public class HomeController : Controller
    {
        public ActionResult Index(IndexModel model)
        {
            //do something here
        }
    }
    

    【讨论】:

      【解决方案3】:

      这两者不能同时存在,因为编译器无法区分它们。重命名它们或删除一个,或者添加一个额外的参数。这适用于所有课程。

      public ActionResult Index(string name) 
      { 
        return new JsonResult(); 
      } 
      
      public ActionResult Index(string lastname) 
      { 
        return new JsonResult(); 
      }
      

      尝试使用带有默认参数的单一方法:

          public ActionResult Index(int? id, string name = null, string lastName = null)
          {
              if (id.HasValue)
              {
                  return new JsonResult();
              }
      
              if (name != null || lastName != null)
              {
                  return new JsonResult();
              }
      
              return View();
          }
      

          public ActionResult Index(int id = 0, string name = null, string lastName = null)
          {
              if (id > 0)
              {
                  return new JsonResult();
              }
      
              if (name != null || lastName != null)
              {
                  return new JsonResult();
              }
      
              return View();
          }
      

      【讨论】:

      • 所有动作只获取http(如web服务)
      猜你喜欢
      • 1970-01-01
      • 2021-10-17
      • 2022-10-12
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 2012-11-30
      • 2010-11-28
      • 1970-01-01
      相关资源
      最近更新 更多