I have a model that looks something like this:
public class SampleModel
{
public static SampleModel Create()
{
return new SampleModel
{
Boolean = true,
// set several more properties...
Colors = new SelectList(new[] { "Red", "Green", "Blue" }, "Green")
};
}
public bool Boolean { get; set; }
// define several more properties...
public SelectList Colors { get; set; }
}
I'm letting ASP.NET MVC automatically scaffold the properties using Html.DisplayForModel()
for my Details view and Html.EditorForModel()
for my Edit view.
Results:
The Edit view works great.
Colors
shows up as a menu with three items (Red, Green, and Blue), and Green is selected by default.For the Details view, however, I get "False True False", which is apparently a list of the
IsSelected
value for each item of the menu. That is definitely not want I want. I would like it to just display "Green".A further problem is that, if I try to do
UpdateModel(sampleModel)
in my controller, I get the error, "No parameterless constructor defined for this object." This is presumably becauseColors
is aSelectList
, and there is no parameterless constructor forSelectList
, so it can't complete the binding.
So, I think I understand what the problems are, but I could really use a good solution for this scenario, which seems to come up a lot when you have models objects with foreign keys.
Some questions:
- How do I get
Colors
to show up as a menu for the Edit view but as just a simple string value (e.g., "Green") in the Details view? - How can I prevent a "no parameterless constructor" error when updating a model that contains a
SelectList
? - If my Model/ViewModel actually contained a foreign key,
ColorId
, instead ofColors
, what would be the best practice for getting the Details view to show the name of the current color and the Edit view to show a menu containing all the color names listed in theColor
table of my database. If it helps, I'm using LinqToSql (SqlMetal) to generate my model classes.