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-->
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With