Session with Ilist on Asp.net mvc5

Asked

Viewed 150 times

0

How do I create a Session with values from an Ilist array on Asp.net mvc5?

If so, how do I foreach to get this information in the view html?

  • is the core version?

  • And then the solution worked out ???

  • Virgilio, to be honest I didn’t test it, because my intention was not to receive Return as Model, I wanted to call it direct by @Session. But his response was of great value, regardless of the return I did not know how to pass an array to Session. I’ll save your answer for future queries.

  • If the answer lacks something, from an improved in your question the rest will be as a complement, and please if it is useful mark as an answer, but edit your question and really ask what you need (maybe I haven’t understood the real focus?

1 answer

0

There’s a way I can create a Session with values of an array of the type IList in Asp.Net Mvc5?

Yes, just add the value in the session as follows:

Configure the application to know that you need to use the Session, open the file at the root of your website Startup.cs and configure two method:

  • 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 the 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 was saved in the session with the name of List but the list has been converted into what the session understands to be a text.

To return to what was before, that is, a text list has to use the reverse process, example:

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

in the previous versions 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, please note:

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:

Save 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); 

Recover from Session:

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

If there is, how do I do the foreach to get this information in the view html?

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

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

and in the View put the setting in @model the kind you need later just do a foreach:

@model List<string>

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

References:

Browser other questions tagged

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