sitBy
sitBy

Reputation: 269

Select from a list passed to view in .NET MVC

Before I had this:

public ActionResult ShowSong(int id)
    {
         return view(db.PublishedSongs.Where(x => x.Id == id).FirstOrDefault());
    }

and in my view:

@model MusicSite.Models.PublishedSong
<h2>@Model.SongName</h2>
@Html.ImageFor(x => x.CoverImageBytes, @Model.SongName + " Image", new { @class = "big-cover-image" })

This worked fine for just retrieving one item from DB and showing on view.

However now, I need to also pass a list to my view, because I want to show all of the items in model and just the select item that was passed through action method, how do I do this? If I pass return View(db.PublishedSongs); to view then I no longer know which id to get to show just that one item.

Upvotes: 1

Views: 773

Answers (1)

Amogh
Amogh

Reputation: 4573

As I am not that much good in .NET MVC but I will try to answer according to spring MVC knowledge.

The rough idea is to pass list to view as you are mentioned and along with it pass the id that you want to select using ViewBag. Now in view iterate over the list, while iteration check whether id come from iteration is equal to id that you passed in ViewBag.

So in controller :

public ActionResult ShowSong(int id)
{
   ViewBag.SelectId = id;
   return view(db.PublishedSongs);
}

In View :

(Loop over the db.PublishedSongs)
{
   if([email protected])
   {
      //select current PublishedSong
   }
   else
   {
     //otherwise
   }
}

Upvotes: 1

Related Questions