Passing model data to partial view

58 views Asked by At

When I create a partial view, and i want to get some model data, i get this error:

enter image description here

the partial view file is in Pages/Shared folder

the error says that the name Model does not exist in the current context?

I get the same error also adding the @ before Model

enter image description here

here the code snippet:

@model List<Tuple<string, string, bool>>

@{
    foreach (Tuple<string, string, bool> menu in @Model)
    {
        
    }
}

this is how i call the partial, this has no problem whatsoever:

@{
    var t = new List<Tuple<string, string, bool>>();
    t.Add(Tuple.Create("/Veicoli", "Veicoli", true));
    t.Add(Tuple.Create("/Clienti", "Clienti", false));

}
@section Tabs {
    <partial name="_TabsPartial" model="t" />
}

I think maybe the problem is in some configuration in creating the partial view file, how do I fix this?

I expect to be able to access the passed Model in the partial view

1

There are 1 answers

8
Narish On
@foreach (Tuple<string, string, bool> menu in Model
{

}

Invoke razor things using the @ symbol. This will define a block in which C# code is now usable. At runtime, all of these C# expressions will be evaluated and templated into the webpage as HTML, C# backend logic, etc

Your line @model List<Tuple<string, string, bool>> will declare a variable for use called Model but since this is a C# object, it must be used as @Model when on its own

In this case you do not need to use it, as it is if its already wrapped in a @foreach razor block

Please give this a read for a summary of razor syntax