Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set values to ViewBag in ActionFilterAttribute ASP MVC 5?

Hello I would like to create my custom ActionFilterAttribute for each controller in my application, this attribute should set some ViewBag values. Is ActionFilterAttribute would be fine for it and how to get access to viewbag in ActionFilterAttribute ?

like image 462
Arbejdsglæde Avatar asked Jun 25 '14 12:06

Arbejdsglæde


People also ask

How do you set a ViewBag value?

You can assign a primitive or a complex type object as a value to ViewBag property. You can assign any number of properties and values to ViewBag. If you assign the same property name multiple times to ViewBag, then it will only consider last value assigned to the property.

How pass ViewBag value in MVC?

To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.

How do you keep data in your ViewBag?

If you want the previous view bag data to be posted, keep that in a hidden form field. After user submit's the form, It will print " From GET-Totally new value "; Try to avoid dynamic stuff like ViewBag/ViewData for transferring data between your action methods and views.

Can we pass data from view to controller using ViewBag?

ViewBag itself cannot be used to send data from View to Controller and hence we need to make use of Form and Hidden Field in order to pass data from View to Controller in ASP.Net MVC Razor.


1 Answers

You can do like this

public class SomeMsgAttribute : FilterAttribute, IResultFilter {         public void OnResultExecuted(ResultExecutedContext filterContext)         {         }          public void OnResultExecuting(ResultExecutingContext filterContext)         {             filterContext.Controller.ViewBag.Msg= "Hello";         } } 

Using:

[SomeMsg] public ActionResult Index() {     return View(); } 
like image 117
Ilya Avatar answered Sep 21 '22 23:09

Ilya