When I wrote the if and else statement in a foreach loop, I have encountered an error. I'm not sure what went wrong. I even added @if and @var{ }; to the code. But there is still error.
1 Answer
It's not a good idea to mix partial html fragments with conditional C#/Razor code. 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. 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>
}
<a>and parent<div>are not closed.