Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Possible to have an interface as model in view?

Say that I have the following interface:

public interface IUserListVM
{
     IList<string> UserList { get; }
}

and a view model implementing this view model interface:

public class UserListVM : IUserListVM
{
    private IList<string> userList = new List<string>();

    IList<string> UserList
    {
        get { return userList; }
    }
}

is it then possible to have a view that expects a model that inherits the IUserListVM. Say that I have a UserList partial view that looks something like this:

 @model MVCWebsite.Views.IUserListVM

 @foreach (string user in Model.UserList) {
     user
 }

The meaning of this is to have partial views as standalone as possible.

like image 200
Ekenstein Avatar asked Nov 26 '14 16:11

Ekenstein


People also ask

Can we have two model in view in MVC?

In MVC we cannot pass multiple models from a controller to the single view.

Can we have 2 models in a single view?

You can use multiple models in a single view by creating a common model for all the models that are to be used in a single view. To achieve this, refer to the following steps. First, create a new model (common for all models) and refer all other models that are to be used in the same view.

Can a view model have methods?

You can have methods in your ViewModel .

Is it possible to pass a model object to a view from a controller?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.


1 Answers

After your edit - yes that is entirely possible. See dotnetfiddle

like image 195
Vladimirs Avatar answered Sep 18 '22 03:09

Vladimirs