user4633531
user4633531

Reputation:

Why can't the value of ViewBag be cleared after PostBack?

My controller name is "demo". I write 2 actions with the same name "Index". The first uses [HttpGet] and the seconds is [HttpPost].

But, when I require a PostBack from View, the value of ViewBag.Name in the action [HttpGet] public ActionResult Index() {} can't be cleared.

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

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

In RouteConfig.cs:

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

and the View:

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

@ViewBag.Name

Here is my problem: When I click the button, the value of @ViewBag.Name in the page is "HttpPost". But, in URL, it's /demo/index/HttpGet

Why?

Upvotes: 0

Views: 1165

Answers (2)

user3150241
user3150241

Reputation: 31

Try it :

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

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

Upvotes: 0

DenNukem
DenNukem

Reputation: 8254

If you navigate to this page with a GET request, you're executing method Index(), and as the page is rendered the Name is HttpGet, so it will create the URL for the form action as /demo/index/HttpGet.

Later, once you press the button, you're posting to that very URL created in the previous step, but since the form is POSTing you're executing Index(FormCollection form), and that sets Name to HttpPost. The URL remains what it was generated at the previous step.

Upvotes: 2

Related Questions