简体   繁体   中英

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])

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.

@foreach(var keyValue in Model.CategorySelect.keys)
{
   foreach(var cat in @Model.CategorySelect[keyValue]
   {
      <p>@cat</p> <!--whatever html you fancy--> 
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM