For such a recovery in View, because it has a defined type, you give a CAST for the specified type that you can ideally work with the elements of this List
of KeyValuePair
.
With this list it would look like this:
1) List
In the code
public ActionResult Index()
{
List<KeyValuePair<string, string>> lista = new List<KeyValuePair<string, string>>();
lista.Add(new KeyValuePair<string, string>("item1", "value1"));
lista.Add(new KeyValuePair<string, string>("item2", "value2"));
ViewBag.WebConfigPermissao = lista;
return View();
}
Na View
@{
ViewBag.Title = "Home Page";
List<KeyValuePair<string, string>> lista = (List<KeyValuePair<string, string>>)ViewBag.WebConfigPermissao;
}
@foreach (var item in lista)
{
@item.Key @item.Value
}
Get value with Linq depending on the key
@{
ViewBag.Title = "Home Page";
List<KeyValuePair<string, string>> lista = (List<KeyValuePair<string, string>>)ViewBag.WebConfigPermissao;
string value = "";
KeyValuePair<string, string> saida;
saida = lista.ToList().Where(x => x.Key == "item1").FirstOrDefault();
if (saida.Key != null && saida.Value != null)
{
value = saida.Value;
}
}
2) Dictionary (recommend)
In the code:
public ActionResult Index()
{
Dictionary<string, string> lista = new Dictionary<string, string>();
lista.Add("item1", "value1");
lista.Add("item2", "value2");
ViewBag.WebConfigPermissao = lista;
return View();
}
Na View
@{
ViewBag.Title = "Home Page";
Dictionary<string, string> lista = (Dictionary<string, string>)ViewBag.WebConfigPermissao;
}
@foreach (var item in lista)
{
@item.Key @item.Value
}
Get value as key
String saida;
lista.TryGetValue("item1", out saida);
References: