我有一个页面,用户可以在其中输入他们的状态信息,然后其他用户的列表会返回该状态。我正在使用foreach
循环。
一些州有 0 个用户,这导致我得到一个错误:Object reference not set to an instance of an object。我怎样才能克服这个错误?我使用的特定模型称为 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 中接受空模型或只是在运行时跳过代码的任何想法?