Make a Global ViewBag
Asked Answered
N

2

1

Is there a Way to Create a Global ViewBag that can be used in Different Views.

In my application's scenario, 1)I have used a DropDown for Company that is used into _Layout.cshtml page.

2) For that Dropdown I am passing the Value by making ViewBag.Company in each action.

I want the solution::

1) A Global ViewBag.Company having List that we are passing from each action.

2) Then there won't be any need to create ViewBag.Company in each Action.

This question might be something different. But How can we achieve this?

Nichani answered 30/4, 2014 at 6:40 Comment(3)
Why would you put in in a ViewBag then? Any public static method can be called from within your view. Basically, any class with static fields can function as a ViewBag if you want it to (assuming you know the data types, which I assume you do)Firstrate
Because helpers access the viewbag, and static properties are a bad ideaNuncle
Rahul - How do you pass a value from a Layout page to an action? Are you using a post (then you won't get a view). Can you please clarify? Do you have working code where you set the View.Company in each action?Nuncle
T
0

In real world you have mistake in your architecture.

public class CustomNameAttribute : ActionFilterAttribute
{
        public void OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.Company = "Company";
        }
}

I think you need use Authorization and use property User

Toadinthehole answered 30/4, 2014 at 6:52 Comment(0)
N
0

Add a global filter that adds the Company to the view bag.

Basically create an actionfilter:

public class CompanyFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.Controller.ViewBag.Company = "MyCompany";
    }
}

And register it globally

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CompanyFilter()); // Add this line
        filters.Add(new HandleErrorAttribute());
    }
}
Nuncle answered 30/4, 2014 at 6:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.