Asp net mvc modifying view result in onactionexecuted

Introduction

ASP.NET is a popular used for building web applications. One common task in ASP.NET MVC is modifying the view result in the method. In this article, we will explore how to achieve this with .

Modifying View Result in OnActionExecuted

The OnActionExecuted method is a filter that is executed after the action method has been executed. It allows us to modify the result of the action before it is returned to the client. To modify the view result, we can the Result property of the filter context.


public  void OnActionExecuted(ActionExecutedContext filterContext)
{
    if (filterContext.Result is  viewResult)
    {
        // Modify the view result here
        viewResult.ViewBag.Title = "Modified Title";
    }
}

In the above , we check if the result is a ViewResult. If it is, we can access the ViewBag property of the view result and modify its . In this case, we are modifying the Title property to “Modified Title”.

Example: Modifying View Result

Let's consider an example where we want to modify the view result to add a custom message to the ViewBag. We can achieve this by overriding the OnActionExecuted method in a controller.


public class HomeController : Controller
{
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult viewResult)
        {
            viewResult.ViewBag.Message = "Welcome to my website!";
        }
    }

    public IActionResult Index()
    {
         View();
    }
}

In the above example, we override the OnActionExecuted method in the HomeController. Inside the method, we check if the result is a ViewResult and then add a custom message to the ViewBag. This message can be accessed in the corresponding view.

Conclusion

Modifying the view result in the OnActionExecuted method allows us to customize the output of our ASP.NET MVC application. By accessing the Result property of the filter context, we can modify the properties of the view result, such as the ViewBag. This gives us the flexibility to add custom data or modify existing data before it is rendered to the client.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents