Search code examples
c#asp.net-mvcrazorforeachhtml.hiddenfor

Working with Lists in Razor View - Incorrectly Looping


I have been struggling with getting a list returned in my Razor View page. I am passing data to my controller which connects to my service to retrieve the data for me. This works without issue.

However, when I pass it to my Razor View page, it has a problem with the objects. I ended up doing a foreach loop but there are certain object properties that should not be considered a list. When I try to use the "@Html.HiddenFor(m => m.State)" it no longer works and my result output is just a mess of loops on the page. This is the first time I have worked with lists on here and was hoping someone could suggest a way where I can do a foreach loop in some areas where I need it and then have a FirstOrDefault, or something to that effect for the properties that I do not want to iterate over as they are only indicators (e.g. isEmail = 1, for example).

[ Controller ]

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult GetFilters(MembershipVM model)
{                         
    var results = _service.GetFilters(model).ToArray().ToList();
    model.EmailCount = results.Count();

    if (model.EmailCount == 0)
    {
        TempData["ReturnType"] = "Failure";
        TempData["ReturnMessage"] = "No Members were found using the search criteria entered.";
        return RedirectToAction("Index", model);
    }
    else
    {
        return View("SendEmail", results); // passes list to Razor View
    }
}

[ View ]

@using Otan.Models.Members
@using Otan.Web.Helpers
@model List<MembershipVM>

....
<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="bold panel-title">Filters Selected</h3>
    </div>
    <div class="panel-body">
        <ul>
            @if (Model.Zip.ToString() != 0)  @* I get an error here and with every other object in the model *@
            {
                @:<li>By proximity to ZIP Code: within <b>@Model.Distance</b> miles of Zip Code <b>@Model.Zip</b></li>
            }
....
            @Html.HiddenFor(m => m.State)  @* this does not work either unless I include a foreach loop *@
....

TIA

-- Daisy


Solution

  • Try this code you can use Html.HiddenFor without including it in a for-each loop

    @Html.HiddenFor(m=> Model.FirstOrDefault().State)
    

    as for the if statement you can use it the same way like this

    @if(Model.FirstOrDefault().Zip != 0)