When should I use ViewBag/model?

1k views Asked by At

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?

2

There are 2 answers

3
AudioBubble On BEST ANSWER

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)

0
MMM On

use model if you want strongly-typed add Messages to your View Model. Otherwise, stick with ViewBag.