Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach doesn't find nested class

I want to make a model for mvc page like this:

public class Body
{
    public int Id { get; set; }

    public class Hand
    {
        public List<Fingers> fingers { get; set; }
    }

    public class Foot
    {
        public List<Toes> toes { get; set; }
    }

    public class Head
    {
        public Nose nose {get; set;}
        public List<Ears> ears { get; set; }
        public List<Eyes> eyes { get; set; }
    }
}

Then have a class for Fingers like this:

public class Fingers
{
    public int Id { get; set; }
    public string Description { get; set; }
}

Then access it like this in my view:

@model Models.Body
@foreach (var fingers in Model.Hand.Fingers)
{
    @Html.RadioButton("fingerList", fingers.Description)     
}

Am I doing my model wrong? Right now VS doesn't recognize the Model.Hand in the foreach, much less the Model.Hand.Fingers. I don't want to make the @model IEnumerable because this page should only show one person, but it can have multiple lists of fingers, toes, etc.

like image 921
tshoemake Avatar asked Dec 07 '22 22:12

tshoemake


2 Answers

I think you need a property called Fingers in your Body class instead of a nested class called Hand:

public List<Fingers> Fingers { get; set; }

Then you could:

@foreach (var fingers in Model.Fingers)
{
    @Html.RadioButton("fingerList", fingers.Description)     
}
like image 34
Salah Akbari Avatar answered Dec 10 '22 10:12

Salah Akbari


Your Body class has no property Hand on it.

Beyond that, your Hand class has fingers but in razor you refer to it with Fingers.

I don't know if you really intend to have your classes be nested, but you need to add properties onto your Body class for the ones you want (sticking with your property capitalization conventions):

public class Body
{
    public int Id { get; set; }
    public Hand hand { get; set; }
    public Foot foot { get; set; }
    public Head head { get; set; }

    public class Hand
    {
        public List<Fingers> fingers { get; set; }
    }

    public class Foot
    {
        public List<Toes> toes { get; set; }
    }

    public class Head
    {
        public Nose nose {get; set;}
        public List<Ears> ears { get; set; }
        public List<Eyes> eyes { get; set; }
    }
}

and then you need to refer to the properties with casing that matches your properties, not the class names:

@model Models.Body
@foreach (var fingers in Model.hand.fingers)
{
    @Html.RadioButton("fingerList", fingers.Description)     
}

I would also argue that your casing/capitalization is incorrect, but that's not the point of your question.

like image 153
Tim Avatar answered Dec 10 '22 12:12

Tim