Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 - display value from dictionary in view

I suspect this is simple and I'm just missing it.

I have a view model that has a dictionary as one of its properties. This dictionary is for populating an HTML select with the Category when I'm editing a record. There is also a property to indicate the selected CategoryID. However, when I'm just displaying the record I want to display the value of the key/value pair that corresponds with the CategoryID.

My view model:

public class ItemEditVM
{
    public int ItemID { get; set; }
    public int? CategoryID { get; set; }
    public string ItemDesc { get; set; }
    public Dictionary<int, string> CategorySelect { get; set; }
}

I've tried something like this but I've got the function parameters wrong:

@Html.DisplayFor(model => model.CategorySelect.TryGetValue(model.CategoryID, out val))

I've also tried this which fails with no specific error message:

@Html.DisplayFor(model => model.CategorySelect.SingleOrDefault(c=> int.Parse(c.Value) == model.CategoryID).Value)

How can I do this?

Many thanks

THE CORRECT ANSWER (Thanks to Mystere Man)

@Html.DisplayFor(model=>model.CategorySelect[Model.CategoryID.Value])
like image 888
9 revs, 2 users 95% Avatar asked Oct 26 '11 20:10

9 revs, 2 users 95%


2 Answers

Have you tried:

@Model.CategorySelect[Model.CategoryID.Value]

Since as you say, CategoryID won't be null, then this should not be a problem.. unless it could be null, in which case you need to do some validation.

like image 185
Erik Funkenbusch Avatar answered Nov 18 '22 20:11

Erik Funkenbusch


@foreach(var keyValue in Model.CategorySelect.keys)
{
   foreach(var cat in @Model.CategorySelect[keyValue]
   {
      <p>@cat</p> <!--whatever html you fancy--> 
   }
}
like image 32
hidden Avatar answered Nov 18 '22 20:11

hidden