Razor HTML

I have a list of elements that I want to display as the contents of the main one (the main one is not included below). Each element has 3 attributes: section name, label and value. Each element is enclosed in and every time a section changes. I need to open (and close the previous one, if any). I am 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 this: every time the section name changes, the fieldset tag (open and / or closed) is not generated. Where am I mistaken? If I do not use Html.Raw (or @: as an alternative), the VS2010 parser signals an error.

+8
razor
source share
2 answers

A call to Html.Raw returns an IHtmlString ; he writes nothing on the page.

Instead, you should write

 @:</fieldset> 

Using @: makes Razor think of it as plain text, so it doesn't have to be well-formed.


However, you can make your code much cleaner by calling GroupBy and creating a nested foreach .

+14
source share

I really think that using @: to work with such code is an abuse of this escape sequence. The problem should be solved by properly 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

+8
source share

All Articles