MVC3 puts a new line in the text of the ViewBag

I have a MVC3 C # .Net web application. I am going through a DataTable. Some lines import OK, some do not. I want to send the error list back to the list format view. I assign the following text to the 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 br would write a line break in the HTML. Is 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?

+7
source share
3 answers

Use string[] to store your errors. Thus, they are a well-formed and excellent set of errors instead of one long line.

In your controller, initializing the ViewBag property:

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

Your view displays the following errors:

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

Separation of problems

You should not handle markup in your controller (i.e. line breaks or any other DOM elements). Presentation should be processed only by View. Therefore, it would be better to pass string[] .

+8
source

When you throw in your mind, use

 @Html.Raw(ViewBag.Test) 

instead

 @ViewBag.Test 

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

+14
source

This worked for me:

Controller:

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

View:

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

Source: https://habr.com/ru/post/907969/


All Articles