0
@helper MyBody
{
  <div>Hello world!</div>
}

The following works perfectly

@helper MyHelper(Func<HelperResult> myFunc)
{
  <div class="modal-body">
    @(config._html.Raw(myFunc != null ? myFunc().ToHtmlString() : ""));
  </div>
}

@MyHelper(MyBody)

and renders:

  <div class="modal-body">
    <div>Hello World!</div>
  </div>

The following sometimes works properly

@helper MyHelper(Func<HelperResult> myFunc)
{
  <div class="modal-body">
    @if(myFunc != null)
    {
      myFunc();
    }
  </div>
}

@MyHelper(MyBody)

but occasionaly, depending on some still unknown influence, renders:

  <div class="modal-body">
  </div>

One piece of code always renders the same, it doesn't switch behavior when refreshing a page. The (large amount of) surrounding code seems to contain the unknown influence.

Can anyone explain why? What can make Razor go wrong that it doesn't render the "Hello World!" DOM element? I'm used to old-school PHP, which has a simple principle: it renders text, and doesn't care about DOM. Razor doesn't work in the same way?

An article describing the deep internals of the Razor engine would be an acceptable answer.

7
  • 1
    What exactly are you trying to achieve? From reading what you have it sounds like you potentially should be using a PartialView rather than trying to invoke a function from Razor. codeproject.com/Tips/617361/Partial-View-in-ASP-NET-MVC-4
    – Oliver
    Feb 19, 2014 at 13:43
  • MyFunc is not null but returns an empty result. That explains it.
    – JotaBe
    Feb 19, 2014 at 14:13
  • @Oliver I'd like to keep the inserted code inline. You need to put the declaration of a PartialView in a separate file? Interesting concept though, thanks!
    – Pieter
    Feb 19, 2014 at 14:46
  • @JotaBe Nope, I put a breakpoint and stepped through the code, myFunc definitely returns the proper html.
    – Pieter
    Feb 19, 2014 at 14:47
  • Please, try two things: 1) include @Html.Raw("Hello!"); 2) include @Html.Raw(myFunc()); in your conditional block, and outside it, and let me know the result.
    – JotaBe
    Feb 19, 2014 at 16:44

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.