I’m working on my first ASP.NET MVC 3 application and I’m trying to show ingredients of a particular ice cream on a create page.
I’ve got a viewmodel for the page which has a structure something like this:
public class IceCreamViewModel
{
...
public IEnumerable<IngredientViewModel> Ingredients { get; set; }
}
(there are other properties but they aren’t germane to the discussion)
Ingredients gets populated by the Create action on the controller and I’ve verified that it contains the data I want.
The IngredientViewModel has the following structure:
public class IngredientViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsChecked { get; set; }
}
In the Create view I have tried to display the collection of ingredients to allow the user to check which are in the recipe (e.g., peanuts, egg, etc.) and I’m doing something like this:
@Html.EditorFor(m => m.Ingredients)
I’ve written and editor template for this that looks like so:
@model IceCream.ViewModels.Ingredients.IngredientViewModel
<div>
@Html.HiddenFor(m => m.Id)
@Html.LabelFor(m => m.Name)
@Html.CheckBoxFor(m => m.IsChecked)
</div>
What I’d expect to show up is a bunch of labels and checkboxes for each of my ingredients, but what shows up is the correct number of label/checkbox entries but they all say “Name” rather than the ingredient name that is in the IngredientViewModel. So I’m certainly doing something wrong here. It obviously knows that it has N items to iterate through but it isn’t picking up the properties of those items. Guidance?
Update
So, all I ended up doing was switching my LabelFor to a TextBoxFor and my values showed up… as they would, of course. (tired, long day) – @LabelFor uses the name of the property, or the annotated DisplayName for the property. Things work fine now… move along, nothing to see here…
You’re trying to create a label for the
Nameproperty (as if you wanted the user to edit the Ingredient Name), instead of actually showing the name as the label for the checkbox.How about changing:
… to:
Or, better yet: