简体   繁体   English

将if和else放入ASP.NET MVC C#的Foreach循环中

[英]Putting if and else in Foreach loop in ASP.NET MVC C#

When I wrote the if and else statement in a foreach loop, I have encountered an error. 当我在foreach循环中编写if and else语句时,遇到了错误。 I'm not sure what went wrong. 我不确定出了什么问题。 I even added @if and @var{ }; 我什至添加了@if@var{ }; to the code. 代码。 But there is still error. 但是仍然有错误。

It's not a good idea to mix partial html fragments with conditional C#/Razor code. 将部分html片段与条件C#/ Razor代码混合在一起不是一个好主意。 The code might repeat but it's far easier to read and maintain later. 该代码可能会重复,但是以后阅读和维护起来要容易得多。

I may not have captured your intent correctly, but I can read this and understand how the condition affects the output. 我可能没有正确捕捉您的意图,但是我可以阅读此书并了解情况如何影响输出。

@foreach (var item in Model)
{
    var HeaderImage = item.HeaderPath;

    if (image != "")
    {
        var fileSavePath = Path.Combine(@"\\mainPage.com", "");
        <div class="picGallery">
            <img src="@Url.Content(item.HeaderPath)" alt="Image" />

            <a href="@Url.Action("ViewPage", "Home")">
            </a>
            <div class="desc2">
                <p style="font-size: 13;">@item.Text</p>
                <p style="font-size: 13;">@item.text_2</p>
            </div>
        </div>
    }
    else
    {
        <div class="picGallery">
            <img src="@Url.Content(item.HeaderPath)" alt="Image" />

            <a href="@Url.Action("ViewPage", "Home")">
                <div id="scanIcon">
                    <img src=img.png alt="imageView" />
                    <h1 style="font-size: 10px;">View Image</h1>
                </div>
            </a>
            <div class="desc2">
                <p style="font-size: 13;">@item.Text</p>
                <p style="font-size: 13;">@item.text_2</p>
            </div>
        </div>
    }
}

You can shorten this. 您可以缩短此时间。 But you need to be careful to escape the @if the nested blocks of code within html. 但是,您需要注意避免@if在html中嵌套的代码块。 It also becomes more difficult to understand what the output should be. 也很难理解输出应该是什么。

@foreach (var item in Model)
{
    var HeaderImage = item.HeaderPath;

    <div class="picGallery">
        <img src="@Url.Content(item.HeaderPath)" alt="Image" />

        <a href="@Url.Action("ViewPage", "Home")">
            @if (image != "")
            {
                // image exists
                var fileSavePath = Path.Combine(@"\\mainPage.com", "");

                <div>  </div>
            }
            else
            {
                <div id="scanIcon">
                    <img src=img.png alt="imageView" />
                    <h1 style="font-size: 10px;">View Image</h1>
                </div>
            }
        </a>
        <div class="desc2">
            <p style="font-size: 13;">@item.Text</p>
        </div>
    </div>
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM