1

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?

fortran
  • 80
  • 7

1 Answers1

2

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

Yogiraj
  • 1,952
  • 17
  • 29
  • Awesome, it now shows all of tags. But I all of end-of-line are gone so it now looks like one long string. Any chance I can either keep original s or apply any "xml beautifier" that shows proper idents? – fortran May 28 '14 at 17:51
  • You can try using something like this http://stackoverflow.com/questions/4094180/indentation-and-new-line-command-for-xmlwriter-in-c-sharp or use markdown – Yogiraj May 28 '14 at 18:01
  • You can use http://alexgorbatchev.com/SyntaxHighlighter/ or You can try some of these packages for markdown http://www.nuget.org/packages?q=markdown – Yogiraj May 28 '14 at 18:17
  • 1
    You steered me in the right direction, so I am accepting the answer. Final version was to format my string as recommended in http://stackoverflow.com/questions/7744320/c-sharp-xmlelement-outerxml-in-a-single-line-rather-than-format/ and then simply enclose your solution in
     @MvcHtmlString.Create(HttpUtility.HtmlEncode(ViewBag.xmlElement)) 
    – fortran May 28 '14 at 19:06