fortran
fortran

Reputation: 80

in MVC 4 how to render one of view elements as XML text?

In MVC 4 application I trying to build a standard Details view but one of the field is an XML text and I wanted to leave as such on the page. I spend already a couple of hours trying but the best I could do it displays content of XML removing tags.

div class="display-label">
     @Html.DisplayNameFor(model => model.stringElement)
</div>
<div class="display-field">
    @Html.DisplayFor(model => model.stringElement)
</div>

<div class="display-label">
     @Html.DisplayNameFor(model => model.xmlElement)
</div>
<div class="display-field">
    @MvcHtmlString.Create(ViewBag.xmlElement)
</div>

First field is displayed as expected while second one displays all the content but all the tags, end-of-lines in xmlElement string are lost. I saw a reference if whole page was xml I could use text/xml as the page type but this is just one filed in the view. Any ideas?

Upvotes: 1

Views: 1315

Answers (1)

Yogiraj
Yogiraj

Reputation: 1982

Change your view code as below:

If xmlElement is not encoded:

 <div class="display-field">
      @MvcHtmlString.Create(HttpUtility.HtmlEncode(ViewBag.xmlElement).Replace("\n", "<br/>"))
 </div>

If xmlElement is encoded:

  <div class="display-field">
      @MvcHtmlString.Create(HttpUtility.HtmlDecode(ViewBag.xmlElement).Replace("\n", "<br/>"))
 </div>

This will treat your xml as text.

Updated answer based on the comments

You can replace the end of the lines with <br/> tag. That will solve your problem without any external libraries

Upvotes: 2

Related Questions