Session with IList in ASP.NET mvc5

0

How can I create a Session with values of an array of type IList in ASP.NET MVC5?

If you have, how do I do the foreach to get this information in the html of the view?

    
asked by anonymous 20.10.2017 / 20:42

1 answer

0
  

How can I create a Session with values of an array of type IList in Asp.Net Mvc5?

You have yes, just add the value in the session as follows:

Set the application to know that you need to use the Session feature, open the file at the root of your Startup.cs site, and set two methods:

  • ConfigureServices(IServiceCollection services)

    public void ConfigureServices(IServiceCollection services)  
    {
        services.AddMvc();
    
        services.AddDistributedMemoryCache();
        services.AddSession(); // adicionando a session
    }
    

and

  • Configure(IApplicationBuilder app, IHostingEnvironment env)

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseSession(); // adicionando session.
    
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
    
        app.UseStaticFiles();
    
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });     
    }
    

Now in methods of any Controller :

public IActionResult Index()
{            

    IList<string> textos = new List<string>();
    textos.Add("texto 1");
    textos.Add("texto 2");
    textos.Add("texto 3");
    textos.Add("texto 5");

    HttpContext.Session.SetString("Lista", JsonConvert.SerializeObject(textos));

    return View();
}

In the code a text list was created and saved in the session named List but the list was converted into what the session understands to be a text.

To return to what was before, ie a list of text has to use the inverse process, eg:

IList<string> textos = JsonConvert
                .DeserializeObject<List<string>>(HttpContext.Session.GetString("Lista"));

In the previous version this is much more practical, but today in the version Core is like this, but, there is a code that can be used in an extension method in a much simpler way,

public static class Utils
{

    public static void SetObject<T>(this ISession session, string key, T value)
    {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

    public static T GetObject<T>(this ISession session, string key)
    {
        try
        {
            if (session.Keys.Contains(key))
            {
                return JsonConvert.DeserializeObject<T>(session.GetString(key));
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }            
        throw new Exception("Key no present");
    }

}

With these two extension methods creates a better shortcut in your code and can be summed up to this:

Write to Session:

IList<string> textos = new List<string>();
textos.Add("texto 1");
textos.Add("texto 2");
textos.Add("texto 3");
textos.Add("texto 5");

HttpContext.Session.SetObject("Lista", textos); 

Retrieve from Session:

IList<string> textos = HttpContext.Session.GetObject<IList<string>>("Lista");
  

If you have, how do I foreach to get this information in the html of the view?

As you know, there is yes, the first part has been answered to pass View do the following:

public IActionResult About()
{
    IList<string> textos = HttpContext.Session.GetObject<IList<string>>("Lista");
    return View(textos);
}

and in View set the configuration to @model of the type you need then just do a foreach :

@model List<string>

@foreach(string texto in Model)
{
    <div>@texto</div>
}

20.10.2017 / 23:14