I have a big problem and I’m a little bit disappointed. I can’t find a good solution with this problem:
I have CompanyA and CompanyB who specialize Company who has an interface ICompany
in my controller. I then load from different databases, companyA and companyB in my List<company>. In my EditorView, I display the different objects companyA and companyB.
When I’m saving, in my controller, my objects in my list aren’t to type CompanyA and CompanyB, but they are all of type Company.
How can I keep my types when I save?
Here is some code if my explanation is not clear:
My example CompanyViewModel.cs:
public class CompanyViewModel
{
#region Properties
public User User { get; set; }
public ExternalAccounts ExtAccounts { get; set; }
public List<Company> Companies { get; set; } // or List<object> Companies { get; set; }
....
#region Ctor
public CompanyViewModel()
{ }
public CompanyViewModel(ExternalAccounts extAccount, bool iniPrefLanguage = true)
{
//normaly it's load from bdd
...
Companies = new List<Company>();
if (test == true)
{
Companies.Add(new CompanyA()); // call webService
}
if (test2 == true)
{
Companies.Add(new CompanyB());
}
...
#region
}
OR I can have:
public ActionResult EditCompanies()
{
...
// Companies = new List<Company>();
Model.Companies.Add(new CompanyA()); // call webService
Model.Companies.Add(new CompanyB());
return View(Model);
}
public ActionResult SaveCompanies(ComapnyViewModel model)
{
var test = model.Companies.OfType<CompanyA>(); // return null !!!
test = model.Companies.OfType<CompanyB>(); // return null !!!!
test = model.Companies.OfType<Company>(); // return my objects !!!!
return View();
}
in view
@Html.EditorFor(m => m.Companies)
and i have EditorTemplate with Company.cshtml, CompanyA.cshtml, CompanyB.cshtml
During my load in View, each object in my list go to the right EditorTemplate (CompanyA and CompanyB)
But when i save… I have a list of company type only …
Any ideas? Thank you!
What I did is:
I created a view with Company as model, and a partial view with CompanyA as model, and another view with CompanyB as model. Inside CompanyView, I called
Html.Partial("CompanyAView", Model)andHtml.Partial("CompanyBView", Model).I hope this helps.