Renato Leite Renato Leite - 1 month ago 6
C# Question

ASP.NET C# MVC How to get a property of controller from the View?

How to get a property of controller from the View "_Layout.cshtml"?

I have the property "DisplayName" (string) and i need get this property in view.

Answer

You can't access properties of a controller from view or layout because the controller that started particular view is gone by the time view is rendered.

Instead of trying to get access to controller you should pass information via model or ViewBag:

In controller:

ViewBag["DisplayName"] = this.DisplayName;

In views:

@ViewBag.DisplayName

Note that there could be multiple controllers involved into rendering of the page.

Comments