MikeTWebb
MikeTWebb

Reputation: 9279

MVC3 putting a newline in ViewBag text

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?

Upvotes: 8

Views: 16297

Answers (4)

Danimal111
Danimal111

Reputation: 2062

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)

Upvotes: 0

Joe
Joe

Reputation: 369

This worked for me :

Controller:

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

View:

<p class="@ViewBag.MsgColor">
        @Html.Raw(@ViewBag.Msg.Replace(Environment.NewLine, "<br/>"))
 </p>

Upvotes: 0

user596075
user596075

Reputation:

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[].

Upvotes: 8

devstruck
devstruck

Reputation: 1507

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.

Upvotes: 16

Related Questions