I have a question related to my controller in MVC. I want to loop inside my JsonResult GetAfmeldingen
using foreach.
But what I do will not go inside my foreach here is my code as it looks right now
public JsonResult GetJsonAfmeldingen()
{
if (Functions.HasLoginCookie())
{
if (Models.Taken.ActID > 0)
{
foreach (var item in Talent.Afmelding.Fetch(null, Models.Taken.ActID, null, null))
{
return Json(item.Participant.CompleteName, JsonRequestBehavior.AllowGet);
}
return Json("Empty ?? ID = " + Models.Taken.ActID + "", JsonRequestBehavior.AllowGet);
}
else
{
return Json(null, JsonRequestBehavior.AllowGet);
}
}
else
{
return Json(null, JsonRequestBehavior.AllowGet);
}
}
In this example, I return a JsonResult
when the first record in my list hits. I've looked to see if it works but it doesn't. The id is filled but what am I missing here? I am new to MVC.
This will terminate on the first loop of the foreach, is that what you want?
foreach (var item in Talent.Afmelding.Fetch(null, Models.Taken.ActID, null, null))
{
return Json(item.Participant.CompleteName, JsonRequestBehavior.AllowGet);
}
This is probably what doesn't work, since you cannot come into the foreach.
public JsonResult GetJsonAfmeldingen()
{
if (Functions.HasLoginCookie())
{
//This one is probably not filled.
if (Models.Taken.ActID > 0)
{
This could be a possible solution:
public JsonResult GetJsonAfmeldingen(int actID)
{
if (Functions.HasLoginCookie())
{
//Now it is filled if you post it correctly.
if (actID > 0)
{
After that try to test it in a smaller scope. Try to have a breakpoint on this line and see if the list is filled.
var listAfmeldingen = Talent.Afmelding.Fetch(null, Models.Taken.ActID, null, null);
//Breakpoint here
int count = listAfmeldingen.Count;
foreach (var item in listAfmeldingen)
{
return Json(item.Participant.CompleteName, JsonRequestBehavior.AllowGet);
}
Have a look at your routing as well, I use this one:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);