I'm trying myself at a model that uses a generic type that I constrained with a base class.
I get the following error when calling my view:
The model item passed into the dictionary is of type 'MVCTest.Models.TestModel`1[MVCTest.Models.SpecialColumn]', but this dictionary requires a model item of type 'MVCTest.Models.TestModel`1[MVCTest.Models.ColumnBase]'.
Here is an example code to demonstrate the issue:
public class ColumnBase
{
public decimal Id { get; set; }
public string Text { get; set; }
public bool Enabled { get; set; }
public ColumnBase()
{
Enabled = true;
}
public string GetFormattedText(string symbol)
{
return string.Format(Text, symbol);
}
}
public class SpecialColumn : ColumnBase
{
public string Baz { get; set; }
}
public class TestModel<TColumn>
where TColumn : ColumnBase
{
Dictionary<string, TColumn> Columns { get; set; }
}
The Controller:
public ActionResult Test ()
{
var testModel = new TestModel<SpecialColumn>();
return View("", testModel);
}
In the view I tried to use ColumnBase as this should be a shared view that just needs the properties provided by ColumnBase:
@model TestModel<ColumnBase>
What is the correct way to implement something like this?