How to make a Viewbag.list receive a List<Keyvaluepair<string, string>>?

Asked

Viewed 2,696 times

4

How should I pass a list (List<KeyValuePair<string, string>>) for view for 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:

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

1 answer

4


For such recovery in View, as it has a defined type, you give a CAST for the specified type that there you can optimally work with the elements of this List of KeyValuePair.

With that list it would be 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
}

Pick up 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
}

Pick value as key

String saida;
lista.TryGetValue("item1", out saida);

References:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.