Anand
Anand

Reputation: 165

Filtering Data from the Controller and Passing it to the View

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 ?

Upvotes: 0

Views: 475

Answers (1)

st4hoo
st4hoo

Reputation: 2204

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.

Upvotes: 1

Related Questions