Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come internal members in my view model aren't accessible in the view?

I have some internal automatic properties in my view model but my strongly-typed view doesn't see them. Everything is in the same assembly, so why is this happening?

public class MyViewModel {
    public   int PublicProperty { get; set; }
    internal int InternalProperty   { get; set; }
}

.

@*My view*@
@model MyViewModel

@Model.PublicProperty

@Model.InternalProperty @*Causes compilation error*@
like image 717
gabe Avatar asked Apr 27 '11 19:04

gabe


People also ask

What is the difference between View and View Model?

VIEW: ( Platform Specific Code – USER INTERFACE ) What the user sees, The Formatted data. VIEWMODEL: ( Reusable Code – LOGIC ) Link between Model and View OR It Retrieves data from Model and exposes it to the View. This is the model specifically designed for the View.

What should a ViewModel contain?

The viewmodel may expose the model directly, or properties related to the model, for data-binding. The viewmodel can contain interfaces to services, configuration data, etc in order to fetch and manipulate the properties it exposes to the view.

What does @model represent in razor view?

The @model directive provides a cleaner and more concise way to reference strongly-typed models from view files. This works (and is still supported with ASP.NET MVC 3) – but is a little verbose. The above syntax is conceptually the same as before (except with a lot fewer characters).

What does return View () in MVC do?

The default behavior of the View method ( return View(); ) is to return a view with the same name as the action method from which it's called. For example, the About ActionResult method name of the controller is used to search for a view file named About.


1 Answers

Views are compiled in a separate dynamically generated assembly by the ASP.NET runtime. So you cannot use internal properties. You could of course still have internal properties on your model but once you map them to the view model there will be no problem as you should always be passing a view model to the view anyways.

Conclusion: always use only public properties on your view models.

like image 138
Darin Dimitrov Avatar answered Oct 16 '22 18:10

Darin Dimitrov