How to make a ViewBag.list receive a type ListKeyValuePairstring, string?

4

How do I pass a list ( List<KeyValuePair<string, string>> ) to view by ViewBag ?

My code:

string grupo = "ConfigsPortalWebTextos";
List<KeyValuePair<string, string>> lista = new List<KeyValuePair<string, string>>();
var configuracoes = (NameValueCollection)ConfigurationManager.GetSection(grupo);
if (configuracoes != null && configuracoes.Count > 0)
{
   foreach (string key in configuracoes.AllKeys)
   {
      var teste = configuracoes[key];
       lista.Add(new KeyValuePair<string, string>(key, configuracoes[key]));
   }
}

ViewBag.WebConfigPermissao = lista;
@ViewBag.WebConfigPermissao["Cadastro"]

Error :

  

The best method match overloaded System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string,string>>.this[int] has some invalid arguments

    
asked by anonymous 14.05.2014 / 16:33

1 answer

4

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:

14.05.2014 / 16:54