Search code examples
c#.netmodel-view-controllerviewpartial-views

Sending Data To PartialView Which is Called From View


In View I am calling a Partial View like this.

@foreach (var item in Model.OrderBy(x=>x.VariantName))
{
   <partial name="VariantsListItem" model="item" />
}

The Problem is besides model I want to send some data to this partial view. Is it possible to send a viewbag or something like it when I call partial view like this.


Solution

  • Yes, you can use view-data attribute that assigns a ViewDataDictionary to pass to the partial view. You can do this in your case:

    @{
        ViewData["MyData"] = 1;
    }
    
    @foreach (var item in Model.OrderBy(x=>x.VariantName))
    {
       <partial name="VariantsListItem" model="item" view-data="ViewData" />
    }
    

    In the above code, the MyData key value is set to 1 and added to the ViewData collection so you can retrieve the ViewData in your partial view like:

    @{
        int myData= (int)ViewData["MyData"];
    }