Domanda

So, I have two action methods A=public ActionResult PlaceOrder(PlaceOrderVM model) and B=public ActionResult IngredientsDeficiency(). And I want to know IN B if B was a result of redirection from A. Or in general redirection. I just want to prevent users from requesting method B by themselves. But they can see View if it was redirect from server. Hope someone will understand...


Works

[HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public ActionResult PlaceOrder(PlaceOrderVM model)
    {
        if (ModelState.IsValid)
        {
            var cosumed = _pizzaRepository.TryConsumeIngredients(model.PizzaId);
            if (cosumed == false)
            {
                return View("IngredientsDeficiency");
            }

            _pizzaRepository.InsertOrder(model);
            _pizzaRepository.Save();

            return RedirectToAction("Orders", "User");
        }

        return View(model);
    }

Doesn't work

[HttpPost]
    [Authorize]
    [ValidateAntiForgeryToken]
    public ActionResult PlaceOrder(PlaceOrderVM model)
    {
        if (ModelState.IsValid)
        {
            var cosumed = _pizzaRepository.TryConsumeIngredients(model.PizzaId);
            if (cosumed == false)
            {
                return RedirectToAction("IngredientsDeficiency");
            }

            _pizzaRepository.InsertOrder(model);
            _pizzaRepository.Save();

            return RedirectToAction("Orders", "User");
        }

        return View(model);
    }

    [ChildActionOnly]
    public ActionResult IngredientsDeficiency()
    {
        return View("IngredientsDeficiency");
    }

Error: The action 'IngredientsDeficiency' is accessible only by a child request.

È stato utile?

Soluzione 2

One approach is to set a Session variable flag in the public ActionResult PlaceOrder(PlaceOrderVM model) and check that flag in the public ActionResult IngredientsDeficiency(). Also you can use the TempData collection and the data will be stored only for the next request and you would not have to worry about removing it.

If you don't want to use session, you can also change your public ActionResult PlaceOrder(PlaceOrderVM model) to return the result view of IngredientsDeficiency directly.

Altri suggerimenti

you can make use of ChildActionOnlyAttribute action attribute.

See example here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top