HTML在剃刀三元前pression字面 [英] Html literal in Razor ternary expression

查看:122
本文介绍了HTML在剃刀三元前pression字面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做类似以下

<div id="test">
    @(
        string.IsNullOrEmpty(myString)
          ? @:&nbsp;
          : myString   
    )
</div>

以上语法是无效的,我已经尝试了一堆不同的东西,但不能让它的工作。

The above syntax is invalid, I've tried a bunch of different things but can't get it working.

推荐答案

请尝试以下操作:

@Html.Raw(string.IsNullOrEmpty(myString) ? "&nbsp;" : Html.Encode(myString))

不过,我建议你写一个辅助做这件工作,这样你就不必把你的意见纳入面条:

But I would recommend you writing a helper that does this job so that you don't have to turn your views into spaghetti:

public static class HtmlExtensions
{
    public static IHtmlString ValueOrSpace(this HtmlHelper html, string value)
    {
        if (string.IsNullOrEmpty(value))
        {
            return new HtmlString("&nbsp;");
        }
        return new HtmlString(html.Encode(value));
    }
}

然后在你看来简单:

and then in your view simply:

@Html.ValueOrSpace(myString)

这篇关于HTML在剃刀三元前pression字面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆