-1

I want to create a partial view which will be used several times with differents entities.

It seems that the way to do that is to implement interfaces and use generic types. But after a lot of search I still doesn't understand how to use that in my case.

My starting code :

public interface IEntity
{
    string Title { get; set; }
    string TextToDisplay { get; set; }
}
public class MainViewModel
{
    public Vehicule Vehicule{ get; set; }
    public Sector Sector{ 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; }
}

What I saw is that the model of the partial view will look that :

@model GenericModelType<IEntity>

But now, what would the structure of GenericModelType and how to render partial view (what parameter to put in @Html.RenderPartial("_PartialView",?????)

Thanks in advance

Mojtaba Tajik
  • 1,725
  • 16
  • 34
Manta
  • 490
  • 5
  • 18

1 Answers1

0

Your model should be :

@model IEntity

and your render code :

@Html.RenderPartial("_PartialView", model);

To determine model type you can use "is" keyword :

if (model is Sector)
    // Do something

Here is good example for review.

Mojtaba Tajik
  • 1,725
  • 16
  • 34