I have a problem with TempData
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);
}
Being in the view Sucursales.cshtml
I redirect 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
it TempData["RFCCompany"]
is loaded in the controller as null
if it had not been loaded from the controller Sucursales
. How can I avoid the TempData["RFCCompany"]
not to return null
on page refresh DetalleSucursal.cshtml
?
TempData
it has a very short time to live (only until it finishes loading the view).As an alternative instead of you
TempData
could useSession
that will keep the data for the durationsession
or until you delete it manually.If you do not want to use a session variable, it is appropriate to use the
TempData
in conjunction with the methodKeep
to carry the information between redirects . The official documentation says:To keep all the dictionary entries
TempData
is with:To hold a dictionary entry
TempData
you have to specify a key:In your case and a test that I carried out and it worked for me was that
Controller
the value is specified in the same way that you defined it:You would only have to add the following code segment on the view side, the place does not matter but for the organization of the code I would recommend that it be at the beginning:
In this way, for future redirects , the information would be traveling between the requests.
References:
An alternative is to save the client-side information with either
localStorage
orsessionStorage
(Web Storage
).To find out if a browser supports
Web Storage
it, we use this code snippet:It
sessionStorage
is now accessible for the duration of the browsing session. Data is not recoverable if:Example obtained from w3school:Demo w3school sessionStorage
This is the most adaptable to my problem since I do not require the data to be kept for a long time as localStorage is.
But what if we wanted to store that information beyond a session and make it available whether the browser is closed and reopened or if we continue browsing in a different window than the initial one?
This tries to be answered by
localStorage
. This object has the same properties and methods assessionStorage
, but its persistence goes beyond the session.Data is not recoverable if:
Example obtained from w3school:Demo w3school localStorage