Reputation: 15091
I am trying to decipher a project hosted in github. The [TempDate]
attribute in this line seems to be trivial because its existence does not have any effect.
If I am wrong, what is the purpose of that TempDate
attribute in this project? And as it is not a Razor Page project, how can I access StatusMessage
property of SubCategoryController
class from within Index.cshtml
?
I try accessing StatusMessage
from View.cshtml
via @TempData["StatusMessage"]
but it does not render anything.
<!-- Index.cshtml --->
<p>@((string)TempData["StatusMessage"])</p>
// HttpPost Create action method of SubCategoroyController
await _db.SaveChangesAsync();
StatusMessage = "Success";
return RedirectToAction(nameof(Index));
// ConfigureServices of Startup.cs
services.AddSession();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// Configure of Startup.cs
app.UseStaticFiles();
app.UseSession();
The following works but it is not what I want. I want to know the purpose of [TempData]
attribute attached to the property StatusMessage
.
// HttpPost Create action method of SubCategoroyController
await _db.SaveChangesAsync();
TempData["StatusMessage"] = "Success"; // <==== Modified
return RedirectToAction(nameof(Index));
Upvotes: 0
Views: 226
Reputation: 1182
First know that MVC uses razor. If it is MVC it is razor, and Index.cshtml is a a razor file. Anything with .cshtml is razor. So yes your project is a razor project
This attribute will add the class property "StatusMessage" to the tempdata dictionary. To access it, simply call @TempData["StatusMessage"]. You will have to cast it to do any operations to it.
Keep in mind TempData lives for the current request, and the following request. Then it is removed.
To access the TempData when using the TempData attribute like mentioned above, use the key "TempDataProperty-StatusMessage". It appends the "TempDataProperty-" to the key
Upvotes: 1