0

I have two tables Date and Song. Where DateId is foreign key to Song table.

 - Date:
   DateId
   Date
 - Song:
   SongId
   DateId
   Title

Here is the function:

public ActionResult Index()
        {            
            var song = db.TopSongs;
            var model = db.Dates;
            var latestDate = model.OrderByDescending(d => d.Date).FirstOrDefault();
            return View(latestDate);
        }

I need to show: Date SongId Title in View. But return View is taking only one parameter. Is there a way to pass both table data to view?

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
NoviceMe
  • 3,126
  • 11
  • 57
  • 117

2 Answers2

2

There are two options:

  1. Use the ViewBag

    ViewBag.song = db.TopSongs;
    ViewBag.model = db.Dates
    ViewBag.latestDate = model.OrderByDescending(d => d.Date).FirstOrDefault();
    
  2. Create a new class that contains the info you need, and return that (ie, a view model).

Note that 2 is the preferred option as it allows you to maintain strong typing (the ViewBag uses a dynamic type).

Niranjan Singh
  • 18,017
  • 2
  • 42
  • 75
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
2

You need to create a 'View Model';

public class ViewModel
{
    public int SongId { get; set; }
    public DateTime Date { get; set; }
    public string Title { get; set; }
    //More properties that are needed in View
}

And then populate this;

var viewModel = new List<ViewModel> { //Populate code here };

And pass this populated View Model to the View

return (viewModel);

And make a reference to this in the view itself;

@model IEnumerable<ViewModel>

And finally, display in View;

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
    </tr>
}

Please note that the actual properties of your view model will be different, the above code is just to show how you could possibly achieve this.

ChrisBint
  • 12,773
  • 6
  • 40
  • 62
  • Thanks for the code first! I have few more questions. So this ViewModel class will be part of Controller? Or View? Also so this class should call two other classes with Song and Date table and populate all fields? Isnt that like writing duplicate code? As i have already defined classes for Song and Date tables? Thanks again for taking time to write the code! – NoviceMe Aug 24 '12 at 04:44
  • @NoviceMe It will be a seperate class the defines only the properties that are needed to display the information in the view. I understand it may feel like you are duplicating information, but this is a good approach. The View Model should only contain these fields that are needed. Nothing more, nothing less. This class will likely exist in the Models directory that should been created in a new MVC application and would be populated in your controller as above, then reference in the view, as above. – ChrisBint Aug 24 '12 at 04:51