Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HtmlHelper inside Razor "if" statement

I have written an HtmlHelper Extension to format some content based some of our styles. The helpers render the content correctly when not enclosed within an if.

However, when I am trying to wrap them in a razor if statement, nothing is rendering, I suspect it has something to do with the Razor syntax that I am not doing correctly.

Code:

<div class="notice">

    @if (DataModel.UserHasExpired)
    {
       Html.MyCustomNotificationBox("someparameter") // My helper Should render a div
    }

</div>

If I place my notificationbox outside of the if, it works fine. I have also verified that the code is dropping into the block, but none of the markup is generated in the html when I inspect it.

I've tried appening a @ like so, and ending with a colon

@Html.MyCustomNotificationBox("somparameter");

I have even tried @Html.Raw(..with the above..) which completely errors out.

Any ideas?

like image 347
Priest Avatar asked Dec 10 '12 21:12

Priest


People also ask

Which HtmlHelper object method should you use?

We can use this HTML. RadioButton() Helper method using the class to define the HTML elements. This is the loosely typed expansion method function which we can define as input type to select the (<input type="radio" >) element in razor view.

What does HtmlHelper class do?

The HtmlHelper class renders HTML controls in the razor view. It binds the model object to HTML controls to display the value of model properties into those controls and also assigns the value of the controls to the model properties while submitting a web form.

Is Cshtml a Razor?

All Razor files end with . cshtml. Most Razor files are intended to be browsable and contain a mixture of client-side and server-side code, which, when processed, results in HTML being sent to the browser. These pages are usually referred to as "content pages".


2 Answers

Have you tried putting it in text tags (those tags are not sending to client)?

@if (DataModel.UserHasExpired)
{
    <text>@Html.MyCustomNotificationBox("somparameter")</text>
}
like image 171
Sergey Berezovskiy Avatar answered Sep 18 '22 10:09

Sergey Berezovskiy


<p>
   @if (true)
   {
       @Html.Hello("World")
   }
</p>

Works Perfectly fine

like image 29
efkah Avatar answered Sep 19 '22 10:09

efkah