How to display data for various models in Details view using ASP.NET MVC5

0

Greetings, I have a question about how to send or show the data of a table that is related to another, in this case a table Areas contains a department id to which it belongs, but I need to show in the view the name of the department Not the Id, how can I do this? I know it will sound very basic but I need help.

    
asked by Miguel Mártir 12.10.2017 в 08:01
source

1 answer

1

Miguel, you just need some details. The problem is in the way LINQ works in order to optimize loading times when making a request to the BD. Let's give an example

In your Index method you have a query (Suppose you use LINQ) that shows you all the areas.

public ActionResult Index()
    {
        var areas = db.Areas;
        return View(areas.ToList());
    }

in this case you assume that you only need the data from the Area table as they are represented in your BD Area_Name and Department_Id that is stored as an integer. If what you need is to show information of another table involved as in your case Department you should use "Include" in order to specify that you also need to load another table to show your data. So your Index method stays this way:

public ActionResult Index()
    {
        var areas = db.Areas.Include(a => a.Departamento);
        return View(areas.ToList());
    } 

This way in your view you can call the following:

<td>
    @Html.DisplayFor(modelItem => item.Departamento.Nombre)
</td>

I hope it helps you

    
answered by 25.10.2017 в 21:57