8

I have an MVC3 C#.Net web app. I am looping through a DataTable. Some rows are importing OK, some are not. I am wanting to send a list of errors back to the view in a list format. I am assigning the following text to a ViewBag property

Input error on Row(1) Cell(3) Input string was not in a correct format.<br/> Input error on Row(4) Cell(3) Input string was not in a correct format.<br/>

I was hoping the br would write a line break in the HTML. It does not. I want the error message to look like this

Input error on Row(1) Cell(3) Input string was not in a correct format.
Input error on Row(4) Cell(3) Input string was not in a correct format.

Any ideas?

MikeTWebb
  • 9,149
  • 25
  • 93
  • 132

4 Answers4

15

When you throw into your view, use

@Html.Raw(ViewBag.Test)

instead of

@ViewBag.Test

That will signify to the compiler that string is html and does not need to be encoded as such.

devstruck
  • 1,497
  • 8
  • 10
  • @post....this worked but, again, decided to keep the markup language in the View and not the controller. Thanks – MikeTWebb Feb 08 '12 at 19:21
8

Use a string[] to hold your errors. That way they are a well-formed and distinct set of errors instead of just one long string.

In your Controller, initializing the ViewBag property:

ViewBag.Errors = new string[] { "First error", "Second error" };

In your View, displaying these errors:

@foreach (string error in ViewBag.Errors)
{
    @Html.Label(error)
    <br />
}

Separation Of Concerns

You shouldn't be handling markup layout within your Controller (i.e. line breaks, or any other DOM elements). The presentation should be handled solely by the View. Which is why it would be best to pass a string[].

  • 1
    @Shark....I chose this answer based on the "separation of concerns" you mentioned – MikeTWebb Feb 08 '12 at 19:21
  • @MikeTWebb Absolutely, I'm a firm believe that us MVC Developers should strictly adhere to this. It allows for easily maintainable code. –  Feb 08 '12 at 19:45
0

This worked for me :

Controller:

 ViewBag.Msg += Environment.NewLine + "xxxx";

View:

<p class="@ViewBag.MsgColor">
        @Html.Raw(@ViewBag.Msg.Replace(Environment.NewLine, "<br/>"))
 </p>
Joe
  • 349
  • 2
  • 3
0

My preferred way of doing this is to simply add a <br /> to the line time in the controller code as ViewData["msg"] which can then be pulled from the razor page as below.

Controller Code:

ViewData["msg"] = "Your Query <br /> has been processed.";

Razor Form Code:

@Html.Raw(@MsgFormatted)
Danimal111
  • 1,976
  • 25
  • 31