View modes are really a way to go here. I will not dwell on what viewing models, as you have already stated in your code, so I assume that you already know their purpose and functionality. However, for completeness - viewmodels represent only the data that you want to display in your view; assuming the view displays the first and last name of the employee, there is no reason to send the Employee object back when you really only need two of its properties.
According to the definition of a short viewmodel above, to return the viewmodel instead of attaching the returned object to the ViewBag , you simply create a class that will only store the data that you want to present in the view. So, based on your โexpected resultโ, your view model will look something like this:
public class YourViewModel { public string Title { get; set; } public string SmallDescription { get; set; } public string FullDescription { get; set; } public string MobileName { get; set; } public int ModelYear { get; set; } public decimal Price { get; set; } public string Color { get; set; } }
Once you create an instance and run your viewmodel, navigate to it:
var yourViewModel = new YourViewModel();
At the top of your view, declare an @model variable which is of type YourViewModel :
@model YourViewModel
.. and you are good to go. Therefore, if you want to print the name of the mobile device in the view:
@Model.MobileName
Keep in mind that although you can only have one @model for each view, you can still have multiple view modes. This is possible by creating a parent view model to preserve all view-related view modes and set this instead of @model :
public class ParentViewModel {
Once you create an instance and run your viewmodel, navigate to it:
var parentViewModel = new ParentViewModel(); var yourViewModel = new YourViewModel();
This time, at the top of your view, declare the @model type instead of the @model variable:
@model ParentViewModel
.. and you are good to go. Using the same example, if you want to print the name of the mobile device in the view:
@Model.YourViewModel.MobileName
Keep in mind that I did not pay much attention to how you structured your view models, but rather explained how to pass one (or more) viewmodels back to your view and use them instead of the ViewBag (according to your question). In order for your presentations to be truly filled and looking, Stephen Muke's answer is the way to go.