Question

I try to display a TempData list with HTML balise inside. Is it possible to interpret the balise and not only display it ?

This is code example to illustrate what I want.

Controller :

List<string> ls = new List<string>();
ls.Add("<div> First div </div>");
ls.Add("<div> Another div </div>");
ls.Add("<div> Another div again </div>");
TempData.Add("ModelLs", ls);

View :

var ls = (List<string>)TempData["ModelLs"];
foreach (string str in ls)
{
    @str
}

And I'd like to display 3 "real" div on my page (and not 3 "<div> .... </div>"). How can I do that ?

Was it helpful?

Solution 2

If i understood you right, you would like to display string as HTML markup?

var ls = (List<string>)TempData["ModelLs"];
foreach (string str in ls)
{
    @(new HtmlString(str))
}

Html.Raw() works too :

var ls = (List<string>)TempData["ModelLs"];
foreach (string str in ls)
{
    @(Html.Raw(str))
}

OTHER TIPS

Use Html.Raw it returns markup that is not HTML encoded.

var ls = (List<string>)TempData["ModelLs"];
foreach (string str in ls)
{
    Html.Raw(str)
}

Below code worked fine for me

                                       @{var ls = (List<string>)TempData["ModelLs"];}

                                        <ul>
                                        @foreach (var str in ls)
                                        {
                                            if (!string.IsNullOrEmpty(str))
                                            {
                                                <li>
                                                    @Html.Label(str)
                                                </li>
                                                <br />
                                            }
                                        }
                                        </ul>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top