ASP.NET MVC - 简单如果其他

时间:2013-07-16 10:33:14

标签: c# asp.net-mvc if-statement

出于某种原因,我似乎无法理解为什么我的ASP.NET MVC应用程序出现The if block is missing a closing "}" character. Make sure you have a matching "}" character for all the "{" characters within this block, and that none of the "}" characters are being interpreted as markup.错误。

@foreach (var image in Model.Images)
{
    if (counter == Model.Images.Count - 1)
    {
        <div style="float: left; height: 250px; padding-right: 5px;">
    }
    else
    {
        <div style="float: left; height: 200px; padding-right: 5px;">
    }
    ....
    ....

在上述之前,我只是在做:<div style="float: left; height: 200px; padding-right: 5px;">,但是我需要这个,而不是让它看起来更好。

我在If Else声明中做错了什么?

5 个答案:

答案 0 :(得分:2)

你的问题是MVC解析器正在解释你的代码,因为你已经打开了<div>。而不是打开两个,尝试重新编写代码并输出一个:

@foreach (var image in Model.Images)
{

    int height;

    if (counter == Model.Images.Count - 1)
    {
        height = 250;
    }
    else
    {
        height = 200;
    }

    <div style="float: left; height: @(height.ToString()+"px"); padding-right: 5px;">
        ...
        ...
    </div>
}

它也可以以更紧凑的方式完成:

@foreach (var image in Model.Images)
{

    bool condition = (counter == Model.Images.Count - 1)

    <div style="float: left; height: @( condition ? "200px" : "250px"); padding-right: 5px;">
        ...
        ...
    </div>
}

答案 1 :(得分:1)

这应该有效:

@foreach (var image in Model.Images)
{
    if (counter == Model.Images.Count - 1)
    {
        <text><div style="float: left; height: 250px; padding-right: 5px;"></text>
    }
    else
    {
        <text><div style="float: left; height: 200px; padding-right: 5px;"></text>
    }
}

答案 2 :(得分:1)

我会尝试将if / else完全替换为:

 <div style="@(counter == Model.Images.Count - 1 ? "float: left; height: 250px; padding-right: 5px;" : "float: left; height: 200px; padding-right: 5px;")">

答案 3 :(得分:0)

尝试将整个内容包装在@ {...}中。并从现有语法中删除@符号。

答案 4 :(得分:0)

检查是否需要@ foreach,并尝试在@:

前面附加div