Dynamically Inject HTML into an ASP.NET MVC View

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.

  1. 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.
  2. 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.
  3. 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.

Example

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.

View

[sourcecode language=”html”]<div id="licenseMessage">@(ViewBag.LicensingMessage.Length > 0 ? ViewBag.LicensingMessage : String.Empty)</div>[/sourcecode]

Controller

[sourcecode language=”csharp”]ViewBag.LicensingMessage = LicenseManager.GetLicenseStatus();[/sourcecode]

1 Comment

Sign in
classic
Forgot password?
×
Sign up

(*) Required fields

I agree with OptimaSales Terms & Privacy Policy

×