Razor HTML Conditional Output

后端 未结 2 1028
一整个雨季
一整个雨季 2021-01-05 02:53

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 i

相关标签:
2条回答
  • 2021-01-05 03:31

    I really think that the use of @: to work around such code is an abuse of that escape sequence. The problem should be addressed instead by correctly refactoring the code so that balanced tags can be easily written:

    @foreach(var section in Model.GroupBy(i => i.SectionName)) {
        <h2>@section.Key</h2>
        <fieldset>
        @foreach(LocalStorageItem lsi in section) {
            string fld_name = "f_" + lsi.ItemName;
            <div class="row">
                <div class="ls_label">@lsi.ItemName</div>
                <div class="ls_content" name="@fld_name" id="@fld_name">.</div>
            </div>
        }
        </fieldset>
    }
    

    12 lines of code instead of 18

    0 讨论(0)
  • 2021-01-05 03:48

    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.

    0 讨论(0)
提交回复
热议问题