Razor HTML 条件输出 [英] Razor HTML Conditional Output

查看:57
本文介绍了Razor HTML 条件输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目列表,我想作为主要内容输出(下面不包括主要内容).每个项目有 3 个属性:一个部分名称、一个标签和一个值.每个项目都包含在 a 中,每次更改部分名称时,我都必须打开一个(并关闭前一个,如果有的话).我正在使用带有此代码的 Razor 视图:

@foreach(模型中的LocalStorageItem lsi){字符串 fld_name = "f_" + lsi.ItemName;如果(lsi.SectionName != sn){如果(sn!="){Html.Raw("</fieldset>");}sn = lsi.SectionName;<h2>@sn</h2>Html.Raw("
");}<div class="row"><div class="ls_label">@lsi.ItemName</div><div class="ls_content" name="@fld_name" id="@fld_name">.</div>

}@if (Model.Count != 0) {Html.Raw("</fieldset>");}

问题是:每次更改部分名称时,都不会生成字段集标记(打开和/或关闭).我哪里错了?如果我不使用 Html.Raw(或 @: 作为替代),VS2010 解析器会发出错误信号.

解决方案

调用 Html.Raw 返回一个 IHtmlString;它不会向页面写入任何内容.

相反,你应该写

@:

使用 @: 强制 Razor 将其视为纯文本,因此不需要格式良好.

<小时>

但是,通过调用 GroupBy 并创建嵌套的 foreach 循环,可以使您的代码更加简洁.

I have a list of items I want to output as the contents of a main (the main in not included below). Each Item has 3 attributes: a Section Name, a Label and a Value. Each item is enclosed in a and everytime the Section Name changes I have to open a (and close the previous one, if any). I'm using a Razor view with this code:

@foreach (LocalStorageItem lsi in Model) { 
    string fld_name = "f_" + lsi.ItemName;
    if (lsi.SectionName != sn) {
        if (sn != "") { 
            Html.Raw("</fieldset>"); 
        }
        sn = lsi.SectionName;
        <h2>@sn</h2>
        Html.Raw("<fieldset>");              
    }
        <div class="row">
            <div class="ls_label">@lsi.ItemName</div>
            <div class="ls_content" name="@fld_name" id="@fld_name">.</div>
        </div>        
 }
 @if (Model.Count != 0) {
    Html.Raw("</fieldset>");
 }

The problem is: each time the Section Name changes no fieldset tag (open and/or close) is generated. Where am I wrong? If I don't use Html.Raw (or @: as an alternative) the VS2010 parser signals an error.

解决方案

Calling Html.Raw returns an IHtmlString; it doesn't write anything to the page.

Instead, you should write

@:</fieldset>

Using @: forces Razor to treat it as plain text, so it doesn't need to be well-formed.


However, your code can be made much cleaner by calling GroupBy and making a nested foreach loop.

这篇关于Razor HTML 条件输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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