0

I have a small scenario :

I fetch data from the database and I want to filter it in my ActionExecuted Filter and then send it to the View. I am accessing the fetched data from the Database using TempData, in my Filter. After I modify the data inside my Filter I want to send it to the View. What are the possible solutions for this ?

1 Answer 1

1

When you modify your TempData inside OnActionExecuted method of your custom filter the view will get that modified TempData by design.

Example:

Filter:

public class MyFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        filterContext.Controller.TempData["key"] += "modified";
    }
}

Controller:

[MyFilter]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        TempData["key"] = "some_value";

        return View();
    }
}

View(Index.cshtml):

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
        @TempData["key"]
    </div>
</body>
</html>

When you run this you will see Index page showing modified data pulled from TempData.

Here is some article explaining action filters feature.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your reply but I not using TempData in my View. I am using : @model System.Collections.Generic.IEnumerable<CountryVM> in my View and then I Enumerate the Model to present the view. Is it possible to update this Model object in my Filter ? The workflow I am thinking is as follow : Before my object gets sent to the view let me catch it in filter, modify and then pass to view. Also can I access objects in Filter without using TempData, ViewBag that are created in Controllers ? Thanks in advance.
Please clarify/edit your scenario. You wrote that you have your data inside TempData ...
Sorry for the confusion, I had to use TempData in order to access my country object inside Filter as suggested by peoples in SO. The workflow I am thinking is as follow : Before my object gets sent to the view let me catch it in filter, modify and then pass to view. Also can I access objects in Filter without using TempData, ViewBag that are created in Controllers ?
Yes. You may acces models. Take a look at this: stackoverflow.com/questions/10416951/…
Thanks a lot. I had been looking for this approach for days :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.