We are migrating from ASPNET MVC5 to ASPNET Core meaning we need to refactor some code.
We were using Session = model to store the model in the session, then retrieving it from another Controller.
We understand this option has been discontinued in Core.
We have attempted to use:
HttpContext.Session.SetString("Data", JsonConvert.SerializeObject(model));
However, when Deserialising by using:
var json = HttpContext.Session.GetString("Data");
var model = JsonConvert.DeserializeObject<SearchListViewModel>(json);
The resulting model does not come back the same - it is one long string rather than a structured list (which is was before Serialising).
Is there a better way to achieve passing a model from one controller to another?
CodePudding user response:
you can still use session if you need. You just need to config it in startup
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSession();
....another your code
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
... another your code
}
CodePudding user response:
Assuming that you have configured your Session
in your Startup.cs
, an example of how you can do this:
Create a model class of your object type (whatever you want to store). I am giving a simple example:
public class SearchListViewModel
{
public int SearchID{ get; set; }
public string SearchName{ get; set; }
//so on
}
Then create a SessionExtension
helper to set and retrieve your complex object as JSON:
public static class SessionExtensions
{
public static void SetObjectAsJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetObjectFromJson<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}
Then finally set the complex object in your session as:
var search= new SearchListViewModel();
search.SearchID= 1;
search.SearchName= "Test";
HttpContext.Session.SetObjectAsJson("SearchListViewModel", search);
To retrieve your complex object in your session:
var searhDetails = HttpContext.Session.GetObjectFromJson<SearchListViewModel>("SearchListViewModel");
int searchID= SearchListViewModel.SearchID;
string searchName= SearchListViewModel.SearchName;