Skip to content Skip to sidebar Skip to footer

Mvc 5 Razor View Not Rendering Html Within If Condition

This is the MVC 5 razor view code: ForestView.cshtml @model Forest.Tree @{ var resultHtml = string.Empty; }
Copy

The @: switches to output mode. Note: if you had used something that was clearly markup, it would have switched automatically. For example:

<div>@Html.Raw(resultHtml)</div>

Solution 2:

I was also facing the same issue but I could make it to working. I wanted to open a div start and conditionally end it within a for loop.

Put any dummy HTML element before the @Html.Raw

<div id="divTreeSearchResult">
@if(Model.TreeResultObj != null)
 {
  resultHtml = Html.ContentFromPartial("_TreeReport", Model.TreeResultObj);
  <span>dummySpan</span>@Html.Raw(resultHtml);    
  @Html.Raw(HttpUtility.HtmlDecode(resultHtml)); 
  @Html.Raw(resultHtml);   
  @Html.Raw(HttpUtility.HtmlDecode(resultHtml)); 

 Model.resultStringSaved  = resultHtml;
 @Html.DisplayText("resultStringSaved"); 

 @Html.Raw("<text>Test</text>") 

}

@Html.Raw(Model.resultStringSaved) 
@Html.Raw(HttpUtility.HtmlDecode(Model.resultStringSaved)) 
@Html.DisplayText("resultStringSaved") 

@Html.Raw("<text>Test</text>") 
</div>

After you place a dummy html element there all the below @Html.Raw will work

Happy Coding

Tarak

Solution 3:

1 - And the content from render should be violating HTML syntax and Razor normally doesn't render wrong HTML content. 2 - Enclose the HTML.Raw(resultHtml) into dev.

Solution 4:

After zillions of tests in a full-day: Change use of:

@Html.Raw(Html.DisplayFor(modelItem => item.Mensagem)) 

by:

@Html.Raw(Html.DisplayTextFor(modelItem => item.Mensagem))

You will get the rendered HTML withou any <>!!!

Post a Comment for "Mvc 5 Razor View Not Rendering Html Within If Condition"