【发布时间】:2023-04-11 05:14:01
【问题描述】:
我有一个页面,用户可以在其中输入他们的状态信息,然后返回该状态中的其他用户列表。我正在使用foreach 循环。
一些州有 0 个用户,这导致我得到一个错误:对象引用未设置为对象的实例。我怎样才能克服这个错误?我使用的特定模型称为 Profiles。
模型:
public class homepage
{
public List<profile> profile { get; set; }
public PagedList.IPagedList<Article> article { get; set; }
}
控制器:
public ActionResult Index()
{
HttpCookie mypreference = Request.Cookies["cook"];
if (mypreference == null)
{
ViewData["mypreference"] = "Enter your zipcode above to get more detailed information";
var tyi = (from s in db.profiles.OrderByDescending(s => s.profileID).Take(5) select s).ToList();
}
else
{
ViewData["mypreference"] = mypreference["name"];
string se = (string)ViewData["mypreference"];
var tyi = (from s in db.profiles.OrderByDescending(s => s.profileID).Take(5) where se==s.state select s).ToList();
}
return View();
}
观点:
@if (Model.profile != null)
{
foreach (var item in Model.profile)
{
@item.city
}
}
当我得到 Object reference not set to an instance of an object 错误时,@if (Model.profile != null) 行被突出显示,所以我尝试这样做:
public List<profile>? profile { get; set; }
但它没有用。关于如何在 foreach 中接受空模型或只是在运行时跳过代码的任何想法?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 model foreach