Search code examples
c#modelasp.net-mvc-5viewbag

When should I use ViewBag/model?


I think that using ViewBag is faster than model.

My example is:

In the action:

public ActionResult MyAction()
{
   ViewBag.Data = (from m in myDatabase.myTable select m).ToList();
}

In the view:

@foreach(var item in ViewBag.Data)
{
   <tr>
      <td>@item.myColumn</td>
   </tr>
}

By using model:

[Table("tbl_mytable")]
public class MyTable()
{
   public int Id { get; set; }
   public int Column2 { get; set; }
   public int Column3 { get; set; }
   // ...
   public IEnumerable<MyTable> Data { get; set; }
}

in the model:

public class MainClass
{
   public List<MyTable> MyMethod()
   {
      List<MyTable> list = new List<MyTable>();
      // code logic to find data in database and add to list
      list.Add(new MyTable
      {
         Column2 = ...
         Column3 = ...
      });
      return list;
   }
}

in the action:

public ActionResult MyAction()
{
   MainClass mc = new MainClass();
   MyTable model = new MyTable();
   model.Data = mc.MyMethod();
   return View(model);
}

in the view:

@using MyProjectName.Models
@model MyProjectName.Models.MyTable

@foreach(MyTable item in Model.Data)
{
   <tr>
      <td>@item.Column1</td>
   </tr>
}

Both of them are working, and ViewBag is easier than model.

So, can you tell me: When should I use ViewBag/model?


Solution

  • ViewBag is not faster. In both cases your creating a model of List<MyTable>. All the code you have show for creating your 'MyTable' model is pointless - your just creating a new collection containing duplicates from the existing collection. In the controller it just needs to be

    public ActionResult MyAction()
    {
      var model = (from m in myDatabase.myTable select m).ToList();
      return View(model);
    }
    

    and in the view

    @model List<MyProjectName.Models.MyTable> // a using statement is not required when you use the fully qualified name
    @foreach(var item in Model)
    {
      <tr>
        <td>@item.myColumn</td>
      </tr>
    }
    

    And your MyTable model should not have a property public IEnumerable<MyTable> Data { get; set; } unless your creating a hierarchical model.

    Always use models (preferably view model) in you view so you can take advantage of strong typing (vs ViewBag which is dynamic)