在 Razor 视图中使用列表 - 错误循环

Working with Lists in Razor View - Incorrectly Looping

我一直在努力获取在我的 Razor 视图页面中返回的列表。我正在将数据传递到我的控制器,该控制器连接到我的服务以为我检索数据。这没有问题。

但是,当我将它传递到我的 Razor 视图页面时,它的对象有问题。我最终做了一个 foreach 循环,但有些对象属性不应被视为列表。当我尝试使用“@Html.HiddenFor(m => m.State)”时,它不再有效,我的结果输出只是页面上的一团乱麻。这是我第一次在这里使用列表,希望有人可以建议一种方法,让我可以在我需要的某些区域执行 foreach 循环,然后使用 FirstOrDefault,或者对我的属性产生这种效果的东西不想迭代,因为它们只是指标(例如 isEmail = 1)。

[控制器]

[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
    }
}

[查看]

@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

-- 雏菊

尝试使用此代码,您可以使用 Html.HiddenFor 而无需将其包含在 for-each 循环中

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

至于if statement你可以像这样使用它

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