Question

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!!!

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top