Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC Razor: Helper method to render alternate content when empty
    primarykey
    data
    text
    <p>I've got some data, and sometimes that data is blank. Instead of making a bunch of crazy logic on my view I'd rather use a helper method that will render the data if it exists, and render some HTML that just says "N/A" when the string is empty/null.</p> <p>Ideal syntax: <code>@Helpers.RenderThisOrThat(Model.CustomerPhone)</code></p> <p>If the <code>Model.CustomerPhone</code> (a string) is empty it will render this alternate HTML instead: <code>&lt;span class='muted'&gt;N/A&lt;/span&gt;</code></p> <p>Here's what we have so far:</p> <pre><code>@helper RenderThisOrThat(string stringToRender, string methodToGetAlternateText = null) { @RenderThisOrThat(MvcHtmlString.Create(stringToRender), methodToGetAlternateText) } @helper RenderThisOrThat(MvcHtmlString stringToRender, string methodToGetAlternateText = null) { if (string.IsNullOrWhiteSpace(stringToRender.ToHtmlString())) { if (!string.IsNullOrWhiteSpace(methodToGetAlternateText)) { @methodToGetAlternateText } &lt;span class='muted'&gt;N/A&lt;/span&gt; } @stringToRender } </code></pre> <p>This works just fine until we want to pass something other than a string into either parameter. For example when we have an email address we want it to be a link to that email and not just the string of the email.</p> <p><code>@Helpers.RenderThisOrThat(@&lt;a href="mailto:@Html.DisplayFor(m =&gt; m.CustomerEmail)"&gt;@Html.DisplayFor(m =&gt; m.CustomerEmail)&lt;/a&gt;)</code></p> <p>It gives us the error: "Cannot convert lambda expression to type 'string' because it is not a delegate type"</p> <p>We are at a loss for how to make this work... any help here?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload