【问题标题】:Why can't the value of ViewBag be cleared after PostBack?为什么 PostBack 后 ViewBag 的值不能被清除?
【发布时间】:2015-05-30 20:04:17
【问题描述】:

我的控制器名称是“demo”。我写了 2 个同名的动作 "Index"。第一个使用 [HttpGet],第二个使用 [HttpPost]

但是,当我需要 View 的 PostBack 时,无法清除操作 [HttpGet] public ActionResult Index() {}ViewBag.Name 的值。

[HttpGet]
        public ActionResult Index()
        {
            ViewBag.Name = "HttpGet";
            return View();
        }

        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            ViewBag.Name = "HttpPost";
            return View();
        }

在 RouteConfig.cs 中:

routes.MapRoute(
                name: "newroute",
                url: "demo/index/{type}",
                defaults: new { controller = "demo", action = "Index", type = UrlParameter.Optional }
            );

和视图:

<form method="post" action="@Url.Action("Index", "demo", new { type = @ViewBag.Name })">
    <input type="submit" value="Click me" />
</form>

@ViewBag.Name

这是我的问题:当我单击按钮时,页面中@ViewBag.Name 的值是“HttpPost”。但是,在 URL 中,它是 /demo/index/HttpGet

为什么?

【问题讨论】:

  • 可能更好的标题应该说“如何使用 Url.Action 创建 url 到 POST 动作”......(或者可能不是......我想我不确定你到底在看什么为)。
  • 为什么在路由 URL 中包含 HttpGet?这似乎是一件奇怪的事情。

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


【解决方案1】:

如果您使用 GET 请求导航到此页面,则您正在执行方法 Index(),并且在呈现页面时,NameHttpGet,因此它将为表单操作创建 URL 为 /演示/索引/HttpGet。

稍后,一旦您按下按钮,您将发布到在上一步中创建的那个 URL,但由于表单正在发布,您正在执行 Index(FormCollection form),并将 Name 设置为 HttpPost。该 URL 仍然是在上一步中生成的。

【讨论】:

    【解决方案2】:

    试试看:

    [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Name = "HttpGet";
            return View();
        }
    
        [HttpPost]
        public ActionResult Index(FormCollection form)
        {
            ViewBag.Name = "HttpPost";
            return RedirectToAction("Index");
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 2016-12-04
      相关资源
      最近更新 更多