Prevent TempData from becoming null when reloading view

3

I have a problem with TempData when refreshing the view.

This controller assigns a string to TempData :

public ActionResult Sucursales(string rfcCompany)
{
    model.CuentaUser = CuentaUser;
    TempData["RFCCompany"] = rfcCompany;//solo para evitar mandar el rfc por la url nuevamente
    return View(model);
}

While in the view Sucursales.cshtml redirecciono to DetalleSucursal.cshtml , which the controller has this:

public ActionResult DetalleSucursal(int id, int idEmpresa, string CuentaUser){
    ComprobantesModel model = new ComprobantesModel();
    model.idEmpresa = idEmpresa;
    model.idSucursal = id;
    model.CuentaUser = CuentaUser;
    ViewBag.RFCCompany = TempData["RFCCompany"] as string;//para mostrar el RFC en algun lugar de la vista
    return View(model);
}

I have no problem with the first load of the view, the problem comes when I refresh the view DetalleSucursal.cshtml the TempData["RFCCompany"] is loaded in the controller as null as if it had not been loaded from the controller Sucursales . How can I prevent the TempData["RFCCompany"] from becoming null when refreshing the page DetalleSucursal.cshtml ?

    
asked by JuankGlezz 24.03.2017 в 19:51
source

3 answers

1

If you do not want to use a session variable, it is appropriate to use the TempData in conjunction with the Keep method to carry the information between redirects . The official documentation says:

  

Data in a TempDataDictionary object persists only in one   request to the next, unless you check one or more passwords for   retain them using the Keep method.

To keep all dictionary entries TempData is with:

TempData.Keep();

To keep a dictionary entry TempData you have to specify a key:

TempData.Keep("RFCCompany");

In your case and a test that I did and it worked for me was that in the Controller the value is specified in the same way you defined it:

public ActionResult Sucursales(string rfcCompany)
{
    model.CuentaUser = CuentaUser;
    TempData["RFCCompany"] = rfcCompany;//solo para evitar mandar el rfc por la url nuevamente
    return View(model);
}

Only the next segment of code should be added on the side of the view, the place is indifferent but by organization of the code I would recommend that it be at the beginning:

@{
    TempData.Keep("RFCCompany");
}

In this way, for future redirects the information would be traveling between requests.

References:

answered by 24.03.2017 / 23:09
source
2

TempData has a very short lifetime (only until you finish loading the view).

As an alternative instead of TempData you could use Session that will keep the data while the session lasts or until you delete it manually.

public ActionResult Sucursales(string rfcCompany)
{
  model.CuentaUser = CuentaUser;
  Session["RFCCompany"] = rfcCompany;
  return View(model);
}


public ActionResult DetalleSucursal(int id, int idEmpresa, string CuentaUser)
{
  ComprobantesModel model = new ComprobantesModel();
  model.idEmpresa = idEmpresa;
  model.idSucursal = id;
  model.CuentaUser = CuentaUser;
  ViewBag.RFCCompany = Session["RFCCompany"] as string;
  return View(model);
}
    
answered by 24.03.2017 в 21:19
0

An alternative is to save the client-side information either with localStorage or sessionStorage ( Web Storage ).

To know if a browser supports Web Storage we use this snippet of code:

if (typeof(Storage) !== "undefined") {
    // Si soporta Web Storage.
} else {
    // Lo siento! No Soporta Web Storage tu navegador...
}

Now sessionStorage is accessible for the duration of the browsing session. The data is not recoverable if:

  • The browser is closed and reopened.
  • A new independent navigation tab opens and follows browsing on that tab.
  • The navigation window that was being used is closed and open another.
  • Example obtained from w3school: Demo w3school sessionStorage

    function clickCounter() {
      if (typeof(Storage) !== "undefined") {
        if (sessionStorage.clickcount) {
          sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
        } else {
          sessionStorage.clickcount = 1;
        }
        document.getElementById("result").innerHTML = "You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";
      } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
      }
    }
    <p><button onclick="clickCounter()" type="button">Click me!</button></p>
    <div id="result"></div>
    <p>Click the button to see the counter increase.</p>
    <p>Close the browser tab (or window), and try again, and the counter is reset.</p>

    This is the most adaptable to my problem because I do not require the data to be kept for a long time as it is localStorage

    But what happens if we want to store this information beyond a session and that it is available whether the browser is closed and reopened or if we continue navigating in a different window from the initial one?

    This tries to be answered by localStorage . This object has the same properties and methods as sessionStorage , but its persistence goes beyond the session.

    The data is not recoverable if:

  • The browser cache is cleaned.
  • Example obtained from w3school: Demo w3school localStorage

    function clickCounter() {
      if (typeof(Storage) !== "undefined") {
        if (localStorage.clickcount) {
          localStorage.clickcount = Number(localStorage.clickcount) + 1;
        } else {
          localStorage.clickcount = 1;
        }
        document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clickcount + " time(s).";
      } else {
        document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
      }
    }
    <p><button onclick="clickCounter()" type="button">Click me!</button></p>
    <div id="result"></div>
    <p>Click the button to see the counter increase.</p>
    <p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p>
        
    answered by 24.03.2017 в 22:49