aruni
aruni

Reputation: 2752

How to get list of data in Model?

I have ceremony Model and it has id, date.

I want to get ceremonies which are date<= today.

This is my function in service class.

 public virtual IList<Ceremony> GetAllCeremonyByDate(DateTime currentDate)
        {

            var query = from c in _ceremonyRepository.Table
                        where c.ceremony_date >= currentDate
                        select c;
            var countries = query.ToList();
            return countries;

        }

This is my controller.

   public ActionResult DetailForm()
            {

                Ceremony model = new Ceremony();

                var ceremonyDate = _ceremonyService.GetAllCeremonyByDate(DateTime.Now);
                if (ceremonyDate.Count == 0)
                    return Content("No ceremony can be loaded");

                if (ceremonyDate.Count > 0)
                {

                    foreach (var c in ceremonyDate)
                       // My problem


                }

                return View(model);

            }

I don't know how to assign value to model.

Upvotes: 1

Views: 136

Answers (3)

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102378

Since you're returning a IList<Ceremony> your view should accept a model compatible with this type. For example:

Controller

var ceremonies = _ceremonyService.GetAllCeremonyByDate(DateTime.Now);

if (ceremonies.Count == 0)
{
   return Content("No ceremony can be loaded");
}
else
{
    return View(ceremonies);
}

View

@model IEnumerable<Ceremony>

Then you can enumerate your ceremonies in the view like this:

@foreach (var ceremony in Model)
{
  ...
}

I also think you need to correct your logic. Instead of >= use <=.

var query = from c in _ceremonyRepository.Table
            where c.ceremony_date <= currentDate
            select c;

Upvotes: 1

Andrew Cooper
Andrew Cooper

Reputation: 32576

What type is the view expecting?

If it's IEnumerable<Ceremony> (or something similar) then your controller just needs to be:

public ActionResult DetailForm()
{
    var model = _ceremonyService.GetAllCeremonyByDate(DateTime.Now);

    if (model.Count == 0)
    {
        return Content("No ceremony can be loaded");
    }
    else
    {
        return View(model);
    }
}

If the view is expecting a Ceremony then you need to decide which one to send back. If you just want the first valid one then you could do something like:

public ActionResult DetailForm()
{
    var ceremonies = _ceremonyService.GetAllCeremonyByDate(DateTime.Now);

    if (ceremonies.Count == 0)
    {
        return Content("No ceremony can be loaded");
    }
    else
    {
        return View(ceremonies.First());
    }
}

Upvotes: 1

Ammar
Ammar

Reputation: 1068

You would just assign the values to the model instant inside your foreach loop. For example,

model.id = c.id;
model.date=c.date;

Upvotes: 0

Related Questions