0

I am having an issue on how to access variables from different views in mvc. They way I have it set up is I have a modal on a view that I would like to display values from multiple models. I know I have to use a foreach statement to iterate through the items, but I do not know how to access the other ones.

This is how I call the model in the view:

@model IEnumerable<MyApp.Models.Problems>

Here is my model where I am trying to access the values:

public class Problems
    {
        public int Id { get; set; }
        public string Title { get; set; }

        public IEnumerable<MyApp.Models.Category> Categories { get; set; }
        public IEnumerable<MyApp.Models.Type> Types {get; set;}

    }

This is my other models:

public partial class Category
    {
        public int Id { get; set; }
        public string Title { get; set; }
    }

public partial class Type
    {
        public int Id { get; set; }
        public int Order { get; set; }
        public string Description { get; set; }
    }

Here is an example of what I am trying to do:

This calls the Title in my Problems model which is being loaded:

@Html.DisplayNameFor(model => model.Title)

But I want it to be able to call the Category Title in the same view. Anybody have any idea or can point me in the right direction it would be greatly appreciated!!!

1 Answer 1

1

This is how you can use nested foreach loops to achieve what you want:

@foreach (Problems problems in Model)
{
    foreach (Category category in problems.Categories)
    {
        @Html.DisplayNameFor(category => @category.Title)
    }

    ...
}

You may have to add a using statements at the top of your view into include the namespaces that your models are in. ie:

@using MyApp.Models
Sign up to request clarification or add additional context in comments.

3 Comments

Ahhhh, I see. So i added the using part but when I call "in Model.Problems" it gives me an error on Problems saying - does not contain a definition for 'Problems' and no extension method 'Problems' accepting a first argument of type... could be found.
Also it will not allow me to rename category because they are within the same scope.
May bad. That line should read @foreach (Problems problems in Model). I have edited my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.