Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Additional ViewData to a Strongly-Typed Partial View

People also ask

How do I pass ViewData in partial view?

You're almost there, just call it like this: Html. RenderPartial( "ProductImageForm", image, new ViewDataDictionary { { "index", index } } ); Note that this will override the default ViewData that all your other Views have by default.

How do I pass a model into partial view?

To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.


RenderPartial takes another parameter that is simply a ViewDataDictionary. You're almost there, just call it like this:

Html.RenderPartial(
      "ProductImageForm", 
       image, 
       new ViewDataDictionary { { "index", index } }
); 

Note that this will override the default ViewData that all your other Views have by default. If you are adding anything to ViewData, it will not be in this new dictionary that you're passing to your partial view.


To extend on what womp posted, you can pass new View Data while retaining the existing View Data if you use the constructor overload of the ViewDataDictionary like so:

Html.RenderPartial(
      "ProductImageForm", 
       image, 
       new ViewDataDictionary(this.ViewData) { { "index", index } }
); 

@Html.Partial("_Header", new ViewDataDictionary { { "HeaderName", "User Management" }, { "TitleName", "List Of Users" } })
or
@{Html.RenderPartial("_Header", new ViewDataDictionary { { "HeaderName", "User Management" }, { "TitleName", "List Of Users" } });}

Partial Page(_Header):

<div class="row titleBlock">
    <h1>@ViewData["HeaderName"].ToString()</h1>
    <h5>@ViewData["TitleName"].ToString()</h5>
</div>

I think this should work no?

ViewData["currentIndex"] = index;

Create another class which contains your strongly typed class.

Add your new stuff to the class and return it in the view.

Then in the view, ensure you inherit your new class and change the bits of code that will now be in error. namely the references to your fields.

Hope this helps. If not then let me know and I'll post specific code.


I know this is an old post but I came across it when faced with a similar issue using core 3.0, hope it helps someone.

@{
Layout = null;
ViewData["SampleString"] = "some string need in the partial";
}

<partial name="_Partial" for="PartialViewModel" view-data="ViewData" />