为什么这个Razor语法会出现编译错误?

时间:2012-04-11 17:21:33

标签: asp.net-mvc asp.net-mvc-3 razor

我要么得到“你需要一个;这里”或“最好的重载匹配有无效的参数”错误。

        <tbody>
            <tr>
            @for (int i = 0; i < startDay; ++i)
            {
                @:<td><span></span><span></span></td>
            }
            @for (int j = startDay; j < ((numberOfDays + startDay) - 1); ++j)
            {
                <td>
                    <span>@startCount</span>
                    <br />
                    <span>
                        @{
                            var todaysEvents = Model.ToList().FindAll(d => d.CalDate.Day == j);
                            foreach(HTMLMVCCalendar.Models.CalendarModel eventsToday in todaysEvents)
                            {
                                foreach(HTMLMVCCalendar.Models.EventModel eventToday in eventsToday.CalEvents)
                                {
                                    @eventToday.DayCode.ToString // error here
                                    @:<br />
                                    @eventToday.Subject // error here
                                    @:<br />
                                    @eventToday.EventDesc //error here
                                } 
                                @:<br /> 
                            }
                        }
                    </span>
                </td>
                if ((j + 1) % 7 == 0)
                {
                    @:</tr><tr>
                }
                @++startCount;
            }
            </tr>
        </tbody>

1 个答案:

答案 0 :(得分:4)

使用<text>元素,而不是在要显示的每个文本前使用@。转换:

foreach(HTMLMVCCalendar.Models.EventModel eventToday in eventsToday.CalEvents)
{
    @eventToday.DayCode.ToString // error here
    @:<br />
    @eventToday.Subject // error here
    @:<br />
    @eventToday.EventDesc //error here
} 

要:

foreach(HTMLMVCCalendar.Models.EventModel eventToday in eventsToday.CalEvents)
{
    <text>
        @eventToday.DayCode:<br />
        @eventToday.Subject:<br />
        @eventToday.EventDesc
    </text>
} 

我还删除了.ToString(缺少括号),因为在使用@符号时,对象会隐式转换为字符串。

另一件事,你有这个代码:

@{
    var todaysEvents = Model.ToList().FindAll(d => d.CalDate.Day == j);
    foreach(HTMLMVCCalendar.Models.EventModel eventToday in eventsToday.CalEvents) 
    {
        ...
    }
}

这会不必要地增加你的嵌套。与我们的直觉相反,以@开头的Razor块实际上并不像在C#中那样形成封闭的范围。因此,您可以将其写为:

@{
    var todaysEvents = Model.ToList().FindAll(d => d.CalDate.Day == j);
}
@foreach(HTMLMVCCalendar.Models.EventModel eventToday in todaysEvents.CalEvents) 
{
    ...
}

正如您所看到的(如果您运行它),仍然可以访问todaysEvents