I have a controller method that looks like this
public ActionResult SpecialOrderSummary(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
JobOrder jobOrder = db.JobOrders.Find(id);
if (jobOrder == null)
{
return HttpNotFound();
}
ViewBag.JobOrderID = jobOrder.ID;
ItemInstance ii = db.ItemInstances.Where(x => x.serialNumber == jobOrder.serialNumber).FirstOrDefault();
Item item = db.Items.Find(ii.ItemID);
var vm = new ItemViewModel
{
ItemId = item.ItemID,
ItemName = item.Name,
Parts = new List<ItemPartViewModel>
{
foreach (ItemHasParts ihp in item.IHP)
{
Part part = db.Parts.Find(ihp.PartID);
new ItemPartViewModel
{
PartId = part.ID,
PartName = part.Name
};
}
} //this is closing method
}; // this is closing controller
return View(vm);
}
But the closing }
to the Parts list and the vm aren't closing the right brackets. Instead, the Parts }
is closing the method while the vm }
is closing the controller.
Why is this happening? Is there an issue with my syntax?
Yea you can't have a foreach
loop inside the Parts
list initialization.
You have to do:
var vm = new ItemViewModel
{
ItemId = item.ItemID,
ItemName = item.Name,
Parts = new List<ItemPartViewModel>()
};
foreach (ItemHasParts ihp in item.IHP)
{
Part part = db.Parts.Find(ihp.PartID);
vm.Parts.Add(new ItemPartViewModel
{
PartId = part.ID,
PartName = part.Name
};
}
I am surprised the compiler actually let you compile?