0

This question has probably been answered a million times, however, I spent over three hours and I can't find an answer to my problem. I am trying to pass two models to my Details view and I have trouble understanding what shall be returned by my Details controller.

These are my models:

public class Property
{
    public int PropertyID { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string ProvinceState { get; set; }
    public string ZipCode { get; set; } 
    public string Country { get; set; }

}

public class PropertySimilar {
    public IEnumerable<Property> Properties { get; set; }
    public Property CurrentProperty { get; set; }
}

This is my controller:

public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Property property = db.Properties.Find(id);

        if (property == null)
        {
            return HttpNotFound();
        }
        return View(db.Properties.ToList());
    }

I am trying to display the select property, in addition to, three other random properties underneath it.

Any guidance would be greatly appreciated. Thanks.

HereToLearn
  • 292
  • 5
  • 16
  • 2
    The simple rule of thumb in such cases is to leverage the viewmodel concept.Keep all the displayed properties in a viewmodel and pass that viewmodel to view. – Navoneel Talukdar Jan 23 '18 at 03:48
  • 2
    You can put both models in a single viewmodel class, and then pass required properties to view. Similar issues can be found [here](https://stackoverflow.com/questions/944334/asp-net-mvc-view-with-multiple-models) and [here](https://stackoverflow.com/questions/17030399/pass-two-models-to-view). – Tetsuya Yamamoto Jan 23 '18 at 03:50
  • Thank you both for the speedy reply, I get it now! So simple.. – HereToLearn Jan 23 '18 at 04:09

1 Answers1

0

With Neel's and Tetsuya's help, I was able to solve my issue. Here is what the controller should look like:

public ActionResult Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    var property = db.Properties.Find(id);

    if (property == null)
    {
        return HttpNotFound();
    }

    PropertySimilar pros = new PropertySimilar();
    pros.CurrentProperty = property;
    pros.Properties = db.Properties.ToList();

    return View(pros);
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
HereToLearn
  • 292
  • 5
  • 16