MVC C# Adding items to to a List<> within foreach
I'm working on something and while I usually have no problems with c# i've had a brain meltdown and got a bit stuck...
Within my MVC app I have a controller which manages some markers for Google Maps (as follows)
public ActionResult GetMarkers()
{
MarkerList markers = getMarkersForMap();
return Json(markers, JsonRequestBehavior.AllowGet);
}
public MarkerList getMarkersForMap()
{
MarkerList ml = new MarkerList();
foreach (var shop in dirRepo.getAllShops())
{
Marker marker = new Marker
{
html = shop.ShopName,
lat = shop.Lat,
lng = shop.Lng,
label = shop.DirectoryID.ToString()
};
ml.markers.Add(marker); // <<<< Object ref not set to an instance of an object
}
return m;
}
I also have a Markers controller as follows:
public class MarkerList
{
public List<Marker> markers { get; set; }
}
public class Marker
{
public string lat { get; set; }
public string lng { get; set; }
public string html { get; set; }
public string label { get; set; }
}
Data is being populated in the foreach no problem, but I want to add the multiple markers into the list so I can pass them back to the calling function and carry on with displaying the results in 开发者_如何学运维my view page. I can add single items no problem by doing this
return new MarkerList {markers = new List<Marker> {marker}};
but how about multiple items??
You need to have initialized list in your MarkerList
to use it. You can initialize it in the default MarkerList
constructor.
public class MarkerList
{
public List<Marker> markers { get; set; }
public MarkerList()
{
markers = new List<Marker>();
}
}
Then, you are sure the inner list is always initialized.
BTW: Why do you want to encapsulate your list in the object that contains this list only? There's no benefit of the MarkerList
class now. Unless this is only shortened for question's needs, it'll be better to remove this class and use List<Marker>
directly.
ml.markers is null because You are using auto properties (without backing store). You need to initialize it in ctor for example.
But one thing looks weird. First why is markers public and not started with capital letter. And more important. What is MarkersList class for when You access inner List? Right now it doesn't make much sense. Either make the inner markerslist private/protected and add AddMarker method to MarkersList. Or just use List in controller and return it.
精彩评论