eXplicit eXplicit - 1 month ago 9
C# Question

Multiple query results on one view

I'm trying to learn C#.net and figured with all the hype around .net core I'd start there, but I'm a little out of my depth.

I have a list of (lets say 'Countries') from a database. I click on a country and it shows me details of the item. This works:

// GET: Database/Details/00000000-0000-0000-0000-000000000000
public async Task<IActionResult> Details(Guid? id)
{
if (id == null)
{
return NotFound();
}

var country = await _context.countries.SingleOrDefaultAsync(s => s.Id == id);
if (subscription == null)
{
return NotFound();
}

return View(country);
}


On the details view, I want to show two tables.

The first being 'country', which will show generic information (Capital, Currency, Continent). I can currently do this fine.

The second being a list of cities (from a table called 'Cities'). How would I do this? I can't work out how to return a second result set to the view.

(Hope the analogy helped explain it!)

Answer

You need to return a ViewModel. So create a class IndexViewModel or how your action is called (this is just a best practice, you can name it how you want) and add 2 properties:

public class IndexViewModel
{
    public Country Country { get; set; }
    public List<City> Cities { get; set; }
}

Then in your controller return the model:

// GET: Database/Details/00000000-0000-0000-0000-000000000000
public async Task<IActionResult> Details(Guid? id)
{
    if (id == null || subscription == null)
    {
        return NotFound();
    }

    var model = new IndexViewModel();
    model.Country = await _context.countries.SingleOrDefaultAsync(s => s.Id == id);
    model.Cities = SomeFunction();

    return View(model);
}

In your View add a reference at the top of the document:

@model IndexViewModel

And, you can access the data by:

@Model.Country
@Model.Cities