Reza.Hoque
Reza.Hoque

Reputation: 2750

Model binding for nested objects

I have a class

 public class Offer
{
    public Int32 OfferId { get; set; }
    public string OfferTitle { get; set; }
    public string OfferDescription { get; set; }

}

and another class

 public class OfferLocationViewModel
{
    public Offer Offer { get; set; }
    public Int32 InTotalBranch { get; set; }
    public Int32 BusinessTotalLocation { get; set; }
}

Now in my controller I have the following

 public ActionResult PresentOffers(Guid id)
    {
        DateTime todaysDate=Utility.getCurrentDateTime();

        var rOffers=(from k in dc.GetPresentOffers(id,todaysDate)
                     select new OfferLocationViewModel()
                     {
                        Offer.  //I dont get anything here..

                     }).ToList();


        return PartialView();
    }

Now the problem is in my controller, I can not access any property of the 'Offer' class !! I thought, since i am creating a new OfferLocationViewModel() and this has a property of type 'Offer', I will be able to access the properties..But I can not.

Can anyone give me some idea about how to do that?

Upvotes: 0

Views: 110

Answers (1)

Dennis Traub
Dennis Traub

Reputation: 51644

In a class initializer like new OfferLocationViewModel { ... } you can only set the immediate properties, i.e. 'Offer = new Offer()'.

You can't access the contained type's properties through the initializer.

Though you can initialize the view model's Offer to a new Offer with the given properties like this:

var rOffers = (from k in dc.GetPresentOffers(id,todaysDate)
               select new OfferLocationViewModel {
                   Offer = new Offer {
                       OfferId = ...,
                       OfferTitle = ...,
                       OfferDescription = ...
                   }
               }).ToList();

Upvotes: 2

Related Questions