0

Good Morning,

I have a very simple question regarding ASP.NET MVC 2 View Models.

I have created the following view model:

 public class ClassifiedsListingDetailsViewModel
    {
        public int ListingID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string ImageURL { get; set; }
        public string Location { get; set; }
        public string ListedBy { get; set; }
        public string ContactDetails { get; set; }
        public string CategoryName { get; set; }
    }

No problems, the problems occur when trying to set the values in the controller:

var listing = db.Listings.Single(l => l.ListingID == id);

        var viewModel = new ClassifiedsListingDetailsViewModel
        {
            ListingID = listing.ListingID;


        };

When ever I trying and set ListingID, which is the first property of the view model it wants me to add a "," rather than a ";". Not sure how to overcome this?

Many Thanks, J

1 Answer 1

2

This has to do with instantiating new objects. If you want to do as you say then simply write:

var listing = db.Listings.Single(l => l.ListingID == id);

        var viewModel = new ClassifiedsListingDetailsViewModel
        {
            ListingID = listing.ListingID    
        };

If you want to instantiate more fields then use the comma as you say:

        var viewModel = new ClassifiedsListingDetailsViewModel
        {
            ListingID = listing.ListingID,
            Title = "Title String"
        };
Sign up to request clarification or add additional context in comments.

2 Comments

Oh Dear, that was a very simple question and to further this to define another property I would simply put a ",". Great, so this view models great, but it shares all but one of its properties with a database table... is there any way to get away from declaring them all over again?
You can just do as in the first example, nothing is forcing you to fill out every property

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.