Executing code only once in ASP.NET MVC 3
I have a partial view I created called "noteEditor". This is displayed inside another partial view called "summary". I want the "noteEditor" partial view to only appear on the page once, no matter how many times the "final" partial view is displayed.
I was hoping to do something like a pivot partial view:
@{
var viewDataNotesEditorRegistered = ViewData["notesEditorRegistered"];
var notesEditorRegistered = (bool)(viewDataNotesEditorRegistered ?? false);
}
@if (!notesEditorRegistered)
{
<div class="notesdialog" style="display: none;">@Html.Partial("NotesEditor")</div>
ViewData["notesEditorRegistered"] = true;
}
however, whenever this code is called ViewData ["notesEditorRegistered"], it returns null.
Is there a more global scope (for the whole page and only for this request)?
thank
+3
source to share
1 answer
You can use HttpContext for this purpose instead of ViewData:
@{
var viewDataNotesEditorRegistered = ViewContext.HttpContext.Items["notesEditorRegistered"];
var notesEditorRegistered = (bool)(viewDataNotesEditorRegistered ?? false);
}
@if (!notesEditorRegistered)
{
<div class="notesdialog">@Html.Partial("NotesEditor")</div>
ViewContext.HttpContext.Items["notesEditorRegistered"] = true;
}
+3
source to share