Our software products display a licensing message at the top of the page if the software is in an evaluation/trial phase or if the software license is not valid. To insert the message into the page using MVC 3 and the Razor view engine, we use a simple, elegant method to add content in a master page layout. You can use the same technique to dynamically add content to your MVC view pages whether you use Razor or another view engine.
- Provide a hook in the view to use to display your dynamic content. We most often use a <div> for a clean container in which to inject HTML. You can also create a hook programatically at run-time using jQuery or other client script to attach to an element in the DOM.
- Add code to your controller to provide data to the view. We use the ViewBag object and you can also use ViewData or any other collection at hand that provides data to the view.
- Reference the controller data in the view to dynamically change the view page layout based on the data from the controller. You have myriad options to choose based on the data.
The simple example below shows how to inject a simple message into the top of a Razor view using the ViewBag collection. The view provides a simple placeholder into which you can inject a message from the controller.