0

I've already created my database.

I have two tables in my database "Categories" and "Contents".

My "Categories" table consists of: Id, CategoryName. My "Contents" table consists of: Id, Link, Category.

I wish to display these two tables in a single view in MVC Razor.

I am to display one table at each view, however I am unable to display two table in a view. Can someone teach me step by step on how to do this?

I do not want to display hardcoded List details.

1
  • 1
    Create viewmodel that consist of fields from this two tables and use that model for rendering Commented Aug 6, 2015 at 10:17

2 Answers 2

3

You can create a ViewModel like:

public class MyViewModel
{
  public List<Category> Categories {get; set;}
  public List<Content> Contents {get; set;}
}

Fill that ViewModel with data in your Controller Action:

public ActionResult Index()
{
  var vm = new MyViewModel();
  vm.Categories = db.GetCategories();
  vm.Contents = db.GetContents();
  return View(vm);
}

In your corresponding view:

@model MyApp.Models.MyViewModel

You can now use @Model anywhere in your view to traverse of the data from 2 sources.

Sign up to request clarification or add additional context in comments.

Comments

0
  1. Pick the right strongly typed Model. This model will contain both "Categories" and "Contents" details.

  2. In your View create two HTML tables eg

<div>
    <table>
      <thead>
        <tr> 
          <th>Column 1</th> <th>Column 2</th>  ...
        </tr>
      </thead>
    <tbody>
      @foreach( var category in Model.Categories )
      {
      <tr>
        <td>@category.detail1</td> <td>@category.detail2</td> ...
      </tr>
      }
    </tbody>
   </table>
</div>

You can create as many of these as you want. Use CSS to reference the outer <div> to style and place your tables on the screen

Comments

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.