开发者

Html.EditorFor shows the correct number of items but not the data

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 ingr开发者_JAVA技巧edient 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 Name property (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:

@Html.LabelFor(m => m.Name)

... to:

 @m.Name

Or, better yet:

@model IceCream.ViewModels.Ingredients.IngredientViewModel
<div>
  @Html.HiddenFor(m => m.Id)
  <label for="@m.Id">@m.Name</label>
  @Html.CheckBoxFor(m => m.IsChecked)
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜