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 ?
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.
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.
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.
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With