我有一个页面,用户可以输入他们的状态信息,然后其他用户列表返回到状态中。我正在使用一个foreach
循环。MVC 3在视图模型中接受null 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
}
}
当我不设置到对象的一个实例对象引用错误,行@if (Model.profile != null)
突出显示,所以我尝试了要做到这一点:
public List<profile>? profile { get; set; }
但它没有奏效。任何想法如何接受一个空的模型在foreach或只是在运行时跳过代码?
如果列表为空,则foreach循环不应该崩溃;它应该只循环0次。它看起来像模型本身是空的,给出错误和奇怪的控制器代码。 – 2013-04-09 15:45:46