0

(MVC5) Strange problem. In one view, I POST to 'testpage' with:

<form id="testbtn" method="post" action='http://localhost:11704/Home/testpage'>
  <input type='submit' value="local testing" />
  @Html.Hidden("key1", "value1")
  @Html.Hidden("key2", "value2")
  @Html.Hidden("key3", "value3")
  @Html.Hidden("key4", "value4")
</form>

The 'testpage' controller action is:

<HttpPost>
Function testpage(formdata As FormCollection) As ActionResult
  Dim newdata As New StringBuilder()
  For Each dataitem In formdata.Keys
    newdata.Append(dataitem.ToString()).Append(" ")
    newdata.Append(formdata(dataitem.ToString()))
    newdata.AppendLine()
  Next
  ViewBag.message = newdata
  Return View()
End Function

And when I use "view source" for the displayed 'testpage' I can see this:

<br />
key1 value1
key2 value2
key3 value3
key4 value4

But that is displayed in the browser like this:

key1 value1 key2 value2 key3 value3 key4 value4

Any ideas why the new lines evidently included in my viewbag are not showing up on screen?

Thanks.

Best Regards, Alan

Krekkon
  • 1,349
  • 14
  • 35
Alan
  • 1,587
  • 3
  • 23
  • 43
  • 1
    Newlines in HTML are ignored by default. See for example [How to make Html.DisplayFor display line breaks?](http://stackoverflow.com/questions/9030763/how-to-make-html-displayfor-display-line-breaks). – CodeCaster Nov 11 '14 at 16:21
  • rather then appening a new line, try: newdata.Append("
    ")
    – Stephen Sugumar Nov 11 '14 at 16:23
  • Place the hidden elements in a div that is styled with `white-space: pre-wrap;` –  Nov 11 '14 at 21:14

2 Answers2

0

You have to use <br /> tags for the new lines in the string what you would like to show at View side.

If you have predefined data, you can replace all of the \r\n or \n occures into <br />.

That simple and easy ;)

Krekkon
  • 1,349
  • 14
  • 35
0

Thanks @CodeCaster for the link. That is helping me to understand there are some quirks with new lines in this environment that I obviously wasn't aware of.

I posted here after 11 posts elsewhere trying to get to the bottom of this. Link. Right after posting here, the answer came in. I had tried the ideas posted above, but thanks for confirming I wasn't crazy with all the variations I tried. In the end, this was the ONLY thing that worked:

@Html.Raw(ViewBag.message.Replace(System.Environment.NewLine, "<br/>"))

Don't yet understand why it has to be this way. Even trying to replace \r\n in the View didn't work, and nothing from the controller would work.

Best Regards, Alan

Alan
  • 1,587
  • 3
  • 23
  • 43