在MVC中包含div内的数组元素

时间:2016-05-30 12:25:53

标签: html asp.net-mvc-4 razor

我想将每个promotion包装在div promo中,但是当我这样做时,它甚至会将c#代码(if语句)打印为HTML。 我做错了什么,如何将每个promotion包裹在一个div中?

    @foreach (var promotions in offer.Promotions)
    {
    <div class="promo">
        if (!string.IsNullOrEmpty(promotions.Name))
        {
            <div class="nbt_div">
            <span class="subheadings">
            Name:
            </span>
            @Html.Raw(promotions.Name)
            </div>
        }

        if (!string.IsNullOrEmpty(promotions.Description))
        {
            <div class="nbt_div">
            <span class="subheadings">
            Description:
            </span>
            @Html.Raw(promotions.Description)
            </div>
        }
    </div>  
}

1 个答案:

答案 0 :(得分:2)

在命令C#

之前使用@字符

&#13;
&#13;
@foreach (var promotions in offer.Promotions)
{
    <div class="promo">
        @if (!string.IsNullOrEmpty(promotions.Name))
        {
        <div class="nbt_div">
            <span class="subheadings">
                Name:
            </span>
            @Html.Raw(promotions.Name)
        </div>
        }
        @if (!string.IsNullOrEmpty(promotions.Description))
        {
        <div class="nbt_div">
            <span class="subheadings">
                Description:
            </span>
            @Html.Raw(promotions.Description)
        </div>
        }
    </div>  
}
&#13;
&#13;
&#13;