0

In a ASP.Net MVC project What are the best practices for deciding when to pass data via the Model or via ViewBag.

In my Model i generally have properties that are used for validation for my entity object.

However in the same Model class i am not sure weather it is good practice to then include properties that are not to do with my business entity but instead the layout of the page. So for example i have many properties that decide weather to render certain parts of my page and messages to display if the users has performed a ajax action.

Below is a sample of code to better explain.

Model

public class MyModel {

[Required(ErrorMessage="The Name field is required")]
 public string Name{ get; set; }

public string SaveSuccessMessage {get; set;}

}

View

@model MyNameSpace.MyModel

<div>
  Some Content......

  Html.TextBoxFor(m => m.Name);
  <input type="button" value="Save Changes" onclick="DoAjaxCall()">
</div>

@If(Model.SaveSuccessMessage != null)
{
 <div class="myClass">
  <a class="close">x</a>
   Model.SaveSuccessMessage
 </div>

}

When a user saves changes the controller then has to tell the PartialView to display a success message generated on the server. I can do this a few ways such as passing it via ViewBag

if(ViewBag.SaveSuccessMessage != null)

However it seems passing it via the Model as shown in my sample is a better option as it is strongly typed and i have all my data i need in one place. But i am not sure if this goes against the MVC philosophy.

The way im handling my Views does then result in very large Model classes for complicated pages. Is passing data like this via model recommended?

user2945722
  • 1,293
  • 1
  • 16
  • 35
  • Better to have it in ViewBag.. Later whenever you want to re-arrange the UI and want to show messages at the top or somewhere else, you can do it easily as message is not part of your model and accessible in any section easily. e.g. in your master page or child views – K D Jul 10 '14 at 15:56

1 Answers1

2

"Best Practice" is to create a ViewModel that includes the data from the Model and any other data (selection lists, etc.) that are necessary to generate the view. Then map the results from the ViewModel back to the Model.

ViewBag is a shortcut to avoid defining a class that seems to be almost exactly like your Model. In practice, you will often find yourself creating a ViewModel for various reasons:

  • Adding properties to your model that you don't want exposed to the view (e.g. password field of a user object)
  • Using strongly-typed properties that don;t exist on the model (e.g. select lists)
  • composite views (data from multiple "models")
  • etc.
D Stanley
  • 149,601
  • 11
  • 178
  • 240