KingKerosin
KingKerosin

Reputation: 3841

Passing object to partial view using ViewData

I'm going to build a helper for my application which uses many wizards. For my views, there is simple call:

@using (var wiz = MyHelper.EditWizard(Translate(Keys.User.ChangePasswordTitle)))
{
    // RenderPartial(...)       
}

whereas MyHelper is a own implementation of HtmlHelper which has the original helper-object encapsulated as a property.

As a wizard can consist of multiple steps, the content can be splitted into multiple partial views. The variable wiz has some public methods I need to access in my partial.

Question is, how can I pass the wiz-object?

Inside the EditWizard() I'm trying to add the wizard to the ViewData.

myHelper.HtmlInternal.ViewData["currentWizard"] = theWizard;

However, in my partial, the ViewData-dictionary is always empty. Currently I try to get the data with

var wiz = (Wizard)ViewData["currentWizard"];

But wiz is always null.

Upvotes: 3

Views: 3317

Answers (2)

KingKerosin
KingKerosin

Reputation: 3841

I' ve ended up using

myHelper.HtmlInternal.ViewContext.HttpContext.Items["currentWizard"] = theWizard;

in my helper-method and vice-versa in my partial view

var wiz = (Wizard)ViewContext.HttpContext.Items["currentWizard"]

Is there anything why this should never ever be used or is it legit?

Upvotes: -1

clarkitect
clarkitect

Reputation: 1730

We use HtmlHelper.Partial which has, as its second argument, an object model:

@Html.Partial("YourWizardOrWhatever", wiz)

Wiz, in this case, is provided as the model for the partial view. You can also forward your entire model:

@Html.Partial("YourWizardOrWhatever", Model)

Or you can use the anonymous type to craft up just a few arguments:

@Html.Partial("YourWizardOrWhatever", new { step = Model.Step, answer = Model.LastAnswerOrSomething })

Upvotes: 5

Related Questions