Search code examples
c#asp.net-mvcrazorasp.net-mvc-viewmodelgeneric-type-argument

Partial View with variable model type


Update from Travis Answer :

public interface IEntity
{
    int Id{get;set;}
    string Name{get;set;}
}
public class Vehicule:IEntity
{
    public int Id{get;set;}
    public string Name{ get; set; }
}
public class Sector:IEntity
{
    public string Id{ get; set; }
    public string Name{ get; set; }
}

and this model for the main View :

public class MainViewModel
{
    public Vehicule Vehicule{ get; set; }
    public Sector Sector{ get; set; }
}

Now I want to implement a form for each entity (It will be a modal form but it's not the point). It will be more complex, but for the exemple it's just :

@Html.TextBoxFor(m=>m.Name)
//etc...

I'm trying to implement the interface with generic type but I don't really understand how to do, especially generic type.

Now I have @model GenericViewModel<IEntity> in my partial view and MainViewModel in my view.

How to pass the model to partial view with the generic type?

@Html.RenderPartial("_PartialView",????)

I think there is something missing in MainViewModel but I tried a lot of things without success.

It would be very helpful if you could tell me what I'm missing.

Thanks


Solution

  • Use an interface to expose properties or behaviors across different types.

    public interface IEntity
    {
        string PropertyA;
        string PropertyB;
        string PropertyC;
    }
    

    Then have each entity inherit this interface

    public class Entity1 : IEntity { ... }
    public class Entity2 : IEntity { ... }
    public class Entity3 : IEntity { ... }
    

    And now in your view you can expose the interface properties to the entities

    @model GenericModelType<IEntity>