Passing values to view in Asp.net MVC3
-
28-06-2021 - |
Frage
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?
Lösung
There are two options:
Use the
ViewBag
ViewBag.song = db.TopSongs; ViewBag.model = db.Dates ViewBag.latestDate = model.OrderByDescending(d => d.Date).FirstOrDefault();
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).
Andere Tipps
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.