Reputation: 2339
I know this is basic question.Need help getting error in List using foreach storing data in List but in the end it give me error that _obj
does not exist in the context
I have ActionResult Page
public ActionResult Index()
{
var _objAdd = new C();
var Get_ClientInfor = example();
foreach (var item in Get_ClientInfor)
{
var _obj = new List<C>();
_objAdd.FirstName = item.Clients.FirstName;
_objAdd.LastName = item.Clients.LastName;
if (item.Clients.DateBirth != null)
_objAdd.Dob = item.Clients.DateBirth.Value;
_objAdd.Gender = item.ClientDemographics.Gender;
_obj.Add(_objAdd);
}
return View(_obj); //error ===>>>
}
Getting Error that _obj
does not exist in the context.
Upvotes: 0
Views: 94
Reputation: 320
You put the _obj variable on foreach, you will only be able to use it in the method. Your need to declare outside the iteration.
Upvotes: 1
Reputation: 13182
You need to swap _objAdd
and _obj
declarations because _objAdd
is an item you want to add to collection in foreach
loop and _obj
is a collection you want to return:
public ActionResult Index()
{
var _obj = new List<C>();
var Get_ClientInfor = example();
foreach (var item in Get_ClientInfor)
{
var _objAdd = new C();
_objAdd.FirstName = item.Clients.FirstName;
_objAdd.LastName = item.Clients.LastName;
if (item.Clients.DateBirth != null)
_objAdd.Dob = item.Clients.DateBirth.Value;
_objAdd.Gender = item.ClientDemographics.Gender;
_obj.Add(_objAdd);
}
return View(_obj);
}
Upvotes: 3
Reputation: 9878
Move the declaration of _obj
outside the foreach
loop.
The lexical scope of variable _obj
is inside the scope defined by the braces {}
. So, the variable _obj is not accessible outside the loop. Once you move the variable outside, it is accessible at the Index method level.
public ActionResult Index()
{
var Get_ClientInfor = example();
var _obj = new List<C>();
foreach (var item in Get_ClientInfor)
{
var _objAdd = new C();
_objAdd.FirstName = item.Clients.FirstName;
_objAdd.LastName = item.Clients.LastName;
if (item.Clients.DateBirth != null)
{
_objAdd.Dob = item.Clients.DateBirth.Value;
}
_objAdd.Gender = item.ClientDemographics.Gender;
_obj.Add(_objAdd);
}
return View(_obj);//error ===>>
}
Upvotes: 2
Reputation: 365
You put the _obj variable on foreach. Your need to declare outside the iteration. Try this:
public ActionResult Index()
{
var Get_ClientInfor = example();
var _obj = new List<C>();
foreach (var item in Get_ClientInfor)
{
var _objAdd = new C();
_objAdd.FirstName = item.Clients.FirstName;
_objAdd.LastName = item.Clients.LastName;
if (item.Clients.DateBirth != null)
{
_objAdd.Dob = item.Clients.DateBirth.Value;
}
_objAdd.Gender = item.ClientDemographics.Gender;
_obj.Add(_objAdd);
}
return View(_obj)
}
Upvotes: 3