Home > Net >  how to loop a service object in the view in MVC
how to loop a service object in the view in MVC

Time:04-12

I have the following code:

@foreach (var item in @ViewBag.list)
     {
      <span>@item.Id </span> 
     }

The ViewBag gets the data from a service that contains a class that gets the data from a database, but I'm getting a null exception error since the ViewBag is null because a user has to first enter a date to be able to get the list of ids.

public async Task<ActionResult> plan_post(DateTime dateselected)
    {
        
            DateTime date = dateselected;
            var plan = await _ps.PlanbyDate(date, date);
            ViewBag.list = plan;
            
           
            return View();
      
       
    }

I'm a student doing an internship can you help me with this?

this is the error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

CodePudding user response:

Fo fixed your problem you must debugging your plan object may be null !!!

But you must check if viewbag null not render foreach

if(ViewBag.list != null)
{
//write for each in here
}

You have more options for pass Model to view.

I recommend you use pass with View function

retune View(plan)

But must declaration datatyoe model in top page view

@model YourDataType
  • Related