Matthew Bonig
Matthew Bonig

Reputation: 2136

Executing code only once in ASP.NET MVC 3

I have a partial view that I have created called "noteEditor". That is rendered inside of another partial view called "summary". I want the "noteEditor" partial view only rendered to a page once regardless of how many times the "summary" partial view is rendered.

I had hoped to do something like inside the summary 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, each time this code is called the ViewData["notesEditorRegistered"] it comes back null.

Is there a more "global" (to the entire page and during only that request) scope?

Thanks

Upvotes: 3

Views: 498

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

You could use the HttpContext for that 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;
}

Upvotes: 3

Related Questions