سؤال

I have a simple relationship for a conference site where I have multiple time slots and I want to display multiple sessions in each time slot.

The code below works correctly, however I've had to use @Html.Raw("..") in the outer code block. If I just try to put raw html (like ABCD right above the first @Html.Raw("") I get a compiler error. I'm pretty new to razor and just don't get how I can make my life simpler and have real html code in the nested foreach and not have to have everything wrapped in a helper method.

thanks.

    @Html.Raw("<table id='myTable' border='1'>")

    @foreach (var sessionTime in Model.SessionsByTime)
    { 
        @Html.Raw("<tr>")
        @Html.Raw("<td>")
        @sessionTime.StartTimeFriendly
        @Html.Raw("</td>")
        @Html.Raw("<td></td>")
        @Html.Raw("</tr>")

        @Html.Raw("<table>")
            foreach (var session in sessionTime.sessionsResults)
            {
            <tr>
                <td width="300"></td>
                <td width="300">@session.Title</td>
            </tr>
            }
        @Html.Raw("</table>")
    }
هل كانت مفيدة؟

المحلول

This should look like thid

<table id='myTable' border='1'>
@foreach (var sessionTime in Model.SessionsByTime)
{ 
    <tr>
      <td>@sessionTime.StartTimeFriendly</td>
      <td></td>
    </tr>
    <table>
        @foreach (var session in sessionTime.sessionsResults)
        {
        <tr>
            <td width="300"></td>
            <td width="300">@session.Title</td>
        </tr>
        }
    </table>
}
</table>

if you need to diplay some text that is not wrapped in an html tag you need to use @::

@foreach(var s in list) {
    @: hello there @s
    <text>this also work instead of @: and is usuful
    when you need more than one line
    </text>
}

if you are inside a code block and not inside an html tag, Razor will assume that you are just writing code that's why @: or <text> is needed

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top