ImJoe
ImJoe

Reputation: 47

@Html.DisplayNameFor not showing data MVC5

I have searched around and not had much luck finding a solution to my exact problem.

Model

public class PageDetailsViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Image { get; set; }

}

Controller

 public ActionResult Search(int SysID)
    {

      var query = from r in _db.Auctions
      from d in _db.Product_Details
      where SysID == d.Id && r.BidStatus == "Open" && d.Id == r.Product_DetailsId
      select new PageDetailsViewModel
      {                            
          Name = d.Name,
          Description = d.Description,
          Image = d.Image

      };
    return View(query);
    }

View

@model IEnumerable<ProjectT.Models.PageDetailsViewModel>

@Html.DisplayNameFor(x => x.Name)

This fails to bring the name through. However, if I use a foreach

@foreach (var item in Model)
{
      @item.Name
}

It brings through the name no problem.

Any help is much appreciated.

Upvotes: 2

Views: 843

Answers (1)

Andrei
Andrei

Reputation: 56716

This extension method shows the value of the DisplayNameAttribute from DataAnnotations namespace. Consider this a label. Typically it is used like this:

[DisplayName("The Name")]
public string Name { get; set; }

And in the view:

@Html.DisplayNameFor(x => x.Name)                     <-- displays The Name

The code above will work only if the model is a single item. For the list case, as you have, you need to do some tricks, say a for loop, so you could do something like:

@Html.DisplayNameFor(x => x[i].Name): @Model[i].Name <-- displays The Name: Bill

Upvotes: 2

Related Questions