A quick post for those looking to display a formatted XML document on an ASP.net Razor web page. The following code is in the controller and used to create the string to get passed through to the view. This example is based on displaying the information pulled from the Azure Management API as mentioned in previous blogs. The data is stored in a SQL Server database.
Function ShowRawXML(serviceOperationId As String, subscriptionName As String) As ActionResult
Dim model As New ShowRawXMLViewModel
Dim op = (From o In _db.ServiceOperations
Where o.ServiceOperationId = serviceOperationId And o.Subscription.FriendlyName = subscriptionName
Select o).Single
model.RawXML = vbCr & Server.HtmlEncode(op.RawXML)
model.SubscriptionName = subscriptionName
model.SubscriptionID = op.Subscription.SubscriptionID
model.ServiceOperationID = serviceOperationId
model.ServiceOperationType = op.Type.Name
Return View(model)
End Function
In the view, we are going to use the @Html.Raw function so we used the Server.HtmlEncode function to make it safe to display in HTML. Next we get to the razor view…
@ModelType AzureManager.Domain.ShowRawXMLViewModel
@Code
ViewData("Title") = "ShowRawXML"
End Code
<h2>Subscription ID [@Model.SubscriptionID] @Model.SubscriptionName</h2>
<h3>Show Raw XML for Service Operation @Model.ServiceOperationID</h3>
<h3>Operation Type: @Model.ServiceOperationType</h3>
<pre>
@Html.Raw(Model.RawXML)
</pre>
<p>
@Html.ActionLink("Back to List", "ServiceOperations", New With {.Id = Model.SubscriptionName})
</p>
Here you notice we display the raw XML inside a <pre></pre> tag. This will preserve the white space in the string. More information on this here: HTML <pre> Tag
Leave a comment