Home > OS >  Viewbag data list won't show in the HTML View
Viewbag data list won't show in the HTML View

Time:05-09

In my ASP.NET MVC application, I'm trying to pass some values from controller to view. For this, I'm using the view bag method.

From the controller, the data is passed to the view.

In the view within the for each loop, it also shows the data in the view bag.

But when it runs, I'm getting an error 'object' does not contain a definition for 'cusName'

This is the controller

var SuggestionList = (from c in db.tbl_Main 
                      where c.Suggestion != null orderby c.CreatedDate descending select new 
                      {
                        cusName = c.CustomerName, 
                        Suggest = c.Suggestion
                      }).Take(3).ToList();
 ViewBag.suggestList = SuggestionList;
 return View();

In the view

  @foreach(var data in ViewBag.suggestList) {
    <li > @data.cusName < /li>
  }

CodePudding user response:

Would suggest creating a model class (concrete type) and returning it as List<ExampleModel> type instead of an anonymous list.

public class ExampleModel
{
    public string CusName { get; set; }
    public string Suggest { get; set; }
}
var SuggestionList = (from c in db.tbl_Main 
    where c.Suggestion != null 
    orderby c.CreatedDate descending 
    select new ExampleModel
    {
        CusName = c.CustomerName, 
        Suggest = c.Suggestion
    })
    .Take(3)
    .ToList();

ViewBag.suggestList = SuggestionList;
return View();
  • Related