asp.net mvc - MVC 3 accept null foreach in the viewModel -
i have page users can enter state information , list of other users come within state. using foreach loop.
some of states have 0 users, leads me error: object reference not set instance of object. how can past error? particular model i'm using called profiles.
the model:
public class homepage { public list<profile> profile { get; set; } public pagedlist.ipagedlist<article> article { get; set; } } the controller:
public actionresult index() { httpcookie mypreference = request.cookies["cook"]; if (mypreference == null) { viewdata["mypreference"] = "enter zipcode above 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) se==s.state select s).tolist(); } return view(); } the view:
@if (model.profile != null) { foreach (var item in model.profile) { @item.city } } when object reference not set instance of object error, line @if (model.profile != null) highlighted, tried this:
public list<profile>? profile { get; set; } but didn't work. ideas of how accept empty model in foreach or skip code @ runtime?
just noticed, you're calling view() not passing model, in view you're referencing model.profile. inevitably model null, , therefore has no profile property access. make sure you're passing model off view in return view(model) call.
follow-up collections
i've found time have variable implements ienumerable<t>, it's best populate empty set on null value. say:
// no-nos (imho) ienumerable<string> names = null; // break kinds of // access reliant on names being populated // e.g. linq extensions // better options: ienumerable<string> names = new string[0]; ienumerable<string> names = enumerable.empty<string>(); ienumerable<string> names = new list<string>(); unless checking if (variable != null && variables.count() > 0) every time want access it, make empty collection , leave @ that.
to come full-circle, long variable populated collection of sort (empty or populated) foreach shouldn't break. skip past code block , not output anything. if you're getting object null error, it's because variable empty , enumerator not retrieved.
Comments
Post a Comment