Search code examples
c#asp.netmodel-view-controllercontrollermodels

ASP.NET MVC Passing Two Models to Details View


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.


Solution

  • 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);
    }