Search code examples
asp.net-corevariableshttp-redirectstatic-variables

The best way to save the String Variable after being redirected Page in ASP.NET CORE


How can I save the form values as a string after the page is redirected?

I use a static variable, if the number of users on the site increases for example 20000, will the site have problems?

Which method is better?

  1. Using a static variable?

  2. session?

  3. Cookies?

  4. ViewBag?

  5. View State?

  6. sql server database?


Solution

  • Actually, There is no the best method, Only the most suitable method. The methods you list above all have their own most suitable use cases.

    From your comment, I think you may wanna redirect to another page with a string parameter, So you can try to use :

    return RedirectToAction("actionName","controllerName",new { Name="xxx"});
    

    It will send a get request: acontrollerName/actionName?Name=xxx.

    Or, if you wanna save that string value for a long time, You can also try to use Session or Database. But one thing you need to consider is that you need to set the session time out according to the actual situation of your project.

    ==========================edited===========================

    I think you can use Session to achieve it.

    public class TestModel
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }
    
    
    public async Task<IActionResult> OnPostSelectMenu(int selectedid)
            {
                TestModel selected = await _db.Table.FindAsync(selectedid);
                 //set session
                HttpContext.Session.SetString("Key", JsonConvert.SerializeObject(selected));
                return RedirectToPage("MyPage");
            }
    
    public async Task<IActionResult> OnGetAsync()
            {
                //......
    
                //get session
                Input = JsonConvert.DeserializeObject<TestModel>(HttpContext.Session.GetString("Key"));
                return Page();
            }