【问题标题】:How Does One Differentiate Between Routes POSTed To In Asp.Net MVC?如何区分在 Asp.Net MVC 中发布的路由?
【发布时间】:2010-05-16 19:48:10
【问题描述】:

我有两个动作,一个接受 ViewModel,一个接受两个参数,一个字符串和一个 int,当我尝试发布到该动作时,它给了我一个错误,告诉我当前请求在两者之间不明确行动。

是否可以向路由系统指示哪个动作是相关的,如果是,它是如何完成的?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 routing asp.net-mvc-routing


    【解决方案1】:

    你可以用 HttpGet HttpPost 来装饰它

    查看“覆盖 HTTP 方法动词”

    http://www.asp.net/learn/whitepapers/what-is-new-in-aspnet-mvc

    您还可以使用 ActionName 属性。在“ActionNameAttribute”下查看

    http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx

    【讨论】:

    • 谢谢 Raj,我的意思是 POST 到这两个动作,如果我不清楚,抱歉。
    • 使用 ActionName 或重命名您的操作并相应地从视图中调用它。
    【解决方案2】:

    You can't overload controller actions,尽管正如 Raj 所说,您可以通过允许它们响应不同的请求(获取、发布等)来区分它们。

    您可能还会发现这很有帮助:How a Method Becomes An Action

    【讨论】:

      【解决方案3】:

      就是这样完成的

      一个简化的例子:

      [HttpGet] // this attribute is't necessary when there are only 2 actions with the same name
      public ActionResult Update(int id)
      {
          return View(new Repository().GetProduct(id));
      }
      
      [HttpPost]
      public ActionResult Update(int id, Product product)
      {
          // handle POST data
          var repo = new Repository();
          repo.UpdateProduct(product);
          return RedirectToAction("List");
      }
      

      如果您需要两个具有完全相同的签名(相同名称和完全相同数量的相同类型的参数)的操作,在这种情况下,您将不得不使用另一个属性,例如这个:

      public ActionResult SomeAction(int id)
      {
          return View(new Repository().GetSomething(id));
      }
      
      [HttpPost]
      [ActionName("SomeAction")]
      public ActionResult SomeActionPost(int id)
      {
          // handle POST data
          var repo = new Repository();
          repo.UpdateTimestamp(id);
          return View(repo.GetSomething(id));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-13
        • 1970-01-01
        • 2012-10-12
        • 1970-01-01
        • 2010-12-09
        • 2018-05-31
        • 2016-03-27
        相关资源
        最近更新 更多