【问题标题】:Clarification of ASP.NET MVC routing and model binding说明 ASP.NET MVC 路由和模型绑定
【发布时间】:2014-08-11 11:58:06
【问题描述】:

在 ASP.NET MVC 中,我最近发现:

这不起作用并导致 HTTP 404。

public class TestController : Controller
{
    [HttpGet]
    [HttpPost]
    public ActionResult Index(TestModel model)
    {
        return View(model);
    }
}

这很好用。

public class TestController : Controller
{
    public ActionResult Index(TestModel model)
    {
        return View(model);
    }
}

这也很好用:

public class TestController : Controller
{
    [HttpGet]
    [ActionName("Index")]
    public ActionResult GetIndex(TestModel model)
    {
        return View("Index", model);
    }

    [HttpPost]
    [ActionName("Index")]
    public ActionResult PostIndex(TestModel model)
    {
        return View("Index", model);
    }
}

我想解释一下为什么第一个版本不起作用,但其他两个版本起作用。如果有人能告诉我如何修改第一个版本以使其工作,我也将不胜感激。我喜欢第一个版本,因为它更简洁(1 个方法而不是 2 个)并且还过滤掉了不必要的 HTTP 方法。

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-routing model-binding


【解决方案1】:

HTTP动词属性是互斥的,一个请求不能同时是GET和POST。相反,您必须这样做:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
public ActionResult Index(TestModel model) { ... }

【讨论】:

  • 我还没接受你的回答。我会在大约 5 分钟后将其标记为已接受 :) 谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
相关资源
最近更新 更多