Reputation: 793
I'm trying to optimize my code and I have a method that I would like to populate the drop downs for a viewmodel depending on which type of viewmodel is supplied to the method. The reason I'm doing this is to reduce redundant code.
I realize I am thinking about this problem in a javascript way, so I think I am making this harder than it needs to be.
Here's the pseudo-code, which doesn't work because you can't change types in C# from what I understand:
What would be the be the best way to solve this problem?
EDIT Added code from ViewModel to clarify my question. I am trying to call the same method from two different controller methods, and provide the common selectlists for the dropdown menus in each.
Here is the common code from the viewmodels:
[Display(Name = "What kind of Stuff?")]
public int? StuffId { get; set; }
public IEnumerable<SelectListItem> StuffTypes { get; set; }
Here is the code from the Controller:
private void populateDropDownsPart2(Part2ViewModel part2viewmodel, PrintViewModel printviewmodel)
{
var currentviewmodel = (some initialization object);
if (part2viewmodel == null)
{
currentviewmodel = printviewmodel;
}
else
{
currentviewmodel = part2viewmodel;
}
var SomeDropDownContent = new SelectList(db.Stuff, "StuffId", "StuffName", studentmeddiet.StuffId);
currentviewmodel.SelectListOfStuff = SomeDropDownContent;
}
Here is the common code from the different views:
@Html.DropDownListFor(m => m.StuffId, Model.StuffTypes,"--Select--",new {name="StuffId" })
Upvotes: 1
Views: 118
Reputation: 8334
From a pure design perspective, you would want an interface:
public interface ISelectableListOfStuff
{
SelectList SelectListOfStuff;
}
Any view model that you want this method to work on, should implement that interface:
public Part2ViewModel : ISelectableListOfStuff
Then your method should take an ISelectableListOfStuff:
private void populateDropDownsPart2(ISelectableListOfStuff selectableViewModel)
You can call that method and pass in any object of a type that implements the ISelectableListOfStuff
interface.
Upvotes: 1