MVC 3 - displaying values ​​from a dictionary in a view

I suspect this is easy, and I just missed it.

I have a presentation model that has a dictionary as one of its properties. This dictionary is intended to populate the selected HTML code when I edit the entry. There is also a property to indicate the selected category code. However, when I just show the entry, I want to display the value of a key / value pair that matches the category identifier.

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 tried something like this, but my function parameters are incorrect:

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

I also tried this, which does not have a special error message:

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

How can i do this?

Many thanks

RIGHT ANSWER (thanks to Mystere Man)

 @Html.DisplayFor(model=>model.CategorySelect[Model.CategoryID.Value]) 
+6
source share
2 answers

You tried:

 @Model.CategorySelect[Model.CategoryID.Value] 

Since, as you say, CategoryID will not be NULL, this should not be a problem. If this cannot be null, then you need to do some checking.

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

Source: https://habr.com/ru/post/900162/


All Articles