Home > database >  asp.net pass model and additional parameters to partial view
asp.net pass model and additional parameters to partial view

Time:09-15

I have a partial view that is getting rendered two times on a page.
Inside the partial view I want to render a div based on a condition. I want to be able to pass this condition (the bool value) into the view but it is not in the model.

Can I pass additional parameters along with the model somehow?

F.e. something like this:

<partial name="DetailPartials/_HeaderPartial" model="Model" /*[shouldRenderDiv=true]*/ />

thanks in advance

CodePudding user response:

You can pass additional parameters using the ViewDataDictionary:

@{
    ViewData["shouldRenderDiv"] = true;
}

<partial name="DetailPartials/_HeaderPartial" for="Model" view-data="ViewData">

Or:

<partial name="DetailPartials/_HeaderPartial" for="Model" view-data='new ViewDataDictionary(ViewData) { { "shouldRenderDiv", true } }'>

And access the parameters inside partial:

@if ((bool)ViewData["shouldRenderDiv"])
{
    <div>...</div>
}

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/partial-tag-helper?view=aspnetcore-6.0#view-data

  • Related