10

I have a Model filed that returns an HTML string with line break BR tag, but How do I display that HTML on the browser ? The problem ins instead putting the line break, the Tag itself displaying on the UI

I tried to put the model within Html.Raw(modelItem => item.Speaking), but it never works as it expecting a string inside, and Cannot convert lambda expression to type 'string' because it is not a delegate type

Below is the code and comments what I've tried.

<div>
  @{          
     string strTest = "<br/>Line 1 <br/> Line 2<br>";
     @Html.Raw(strTest); //This works and display as expected
     @MvcHtmlString.Create(strTest); //This works and display as expected       

     @Html.Raw(Html.DisplayFor(modelItem => item.Speaking)); //This doesn't work, its show the <br />  on the screen     
     @MvcHtmlString.Create(Html.DisplayFor(modelItem => item.Speaking).ToString());   //This doent work, its show the <br />  on the screen  
     @Html.Raw(modelItem => item.Speaking) //This throw error Cannot convert lambda expression to type string                                     
    }

 </div>

Appreciate any help or suggestions. thanks in advance!

tereško
  • 58,060
  • 25
  • 98
  • 150
Srééjîth Náîr
  • 311
  • 2
  • 5
  • 15

4 Answers4

15

Try this :

@(new HtmlString(stringWithMarkup))

and you can create a HTML helper too!:

@helper RawText(string s) {
    @(new HtmlString(s))
}
Oualid KTATA
  • 1,116
  • 10
  • 20
  • Thanks Qualid for the response, but that didn't work. I want to know the way to pass the model value as a input to the HtmlString. @(new HtmlString(Html.DisplayFor(modelItem => item.Speaking).ToString())) This gives me the string with markup. – Srééjîth Náîr Aug 21 '14 at 17:01
  • 3
    i just had to use :) Thanks people who took a look at the query! @Html.Raw(item.Speaking) I got the answer from, http://forums.asp.net/p/2004322/5760921.aspx?p=True&t=635442239935208188&pagenum=1 – Srééjîth Náîr Aug 21 '14 at 17:24
  • It works with MVC 5, in case you just display the HTML content in a view. – VincentZHANG Oct 31 '16 at 22:17
9

In MVC4

Instead of using @Html.Raw(modelItem => item.Speaking)

You can use @Html.Raw(@Model.Speaking.ToString())

It works for me and I hope this help someone else too

Dashrath
  • 2,141
  • 1
  • 28
  • 33
5

You can just omit both DisplayFor and modelItem =>, so:

@Html.Raw(item.Speaking)
MGOwen
  • 6,562
  • 13
  • 58
  • 67
0

MVC 5

@Html.Raw(WebUtility.HtmlDecode(item.Speaking))
Aladein
  • 184
  • 2
  • 13