Search code examples
c#sqlmodel-view-controller

SQL data with new lines does not reflect in mvc view


I have a stored procedure which returns a string as below.

 SET @TempMessage = 'Ok:  1 message in abc table' + char(13) + char(10)
    ....
    SET @TempMessage = @TempMessage +  ' Ok: 1 message in def table' + char(13) + char(10)
    ....
    SET @TempMessage = @TempMessage +  ' Ok: 1 message in ghi table'
    
    SELECT @TempMessage

I want the output in MVC view as below (3 lines)

Ok:  1 message in abc table
Ok:  1 message in def table
Ok:  1 message in ghi table

But the output I am getting is just one line

Ok: 1 message in abc table Ok: 1 message in def table Ok: 1 message in ghi table

In the controller, I tried to replace the string as below

var results = db.storedprocedure().FirstOrDefault()
viewmodel.outputmessage = results.replace(@"\r\n", Environment.NewLine)

but it didn't work.

I have also tried

viewmodel.outputmessage = results.replace(@"\\r\\n", Environment.NewLine)
viewmodel.outputmessage = results.replace("\r\n", Environment.NewLine)
viewmodel.outputmessage = results.replace("\\r\\n", Environment.NewLine)
viewmodel.outputmessage = results.replace(@"\r\n", <br />)

There are similar posts like this, but none of the solutions in there do not seem to work out.

What can I try next?


Solution

  • In HTML all newlines are treated as whitespace. To make them visible as line breaks you need to find the newlines, and in their place render a <br /> tag, like in the following example View code:

    @{
        var str = "--1--/r/n--2--/r/n--3--";
        var lines = str.Split(new[] { "/r/n" }, StringSplitOptions.None);
        foreach (var line in lines)
        {
            @(line)<br />
        }
    }