I'm doing some experimental programming to get caught up with ASP MVC.
I created a project for buildings containing rooms. A very simple one to many relationship. I am trying to get scaffolding to work, and from older MVC examples it looks like this should just work. However, the BuildingId field in Rooms isn't mapping to the Building model - no select list in the view.
My models are:
namespace BuildingManagement.Models
{
public class Building
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Address { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string Province { get; set; }
public string PostalCode { get; set; }
[Display(Name = "Phone")]
[DataType(DataType.PhoneNumber)]
[Required]
public string PhoneMain { get; set; }
[Display(Name = "Contact")]
[Required]
public string ContactName { get; set; }
public string Description { get; set; }
public virtual ICollection<Room> Rooms { get; set; }
}
}
and
namespace BuildingManagement.Models
{
public class Room
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Type { get; set; }
public int BuildingId { get; set; }
}
}
I generated the controller with views using Entity Framework, it created the forms but not with the expected Building select list in the Room edit view. It displays an integer input field instead.
What am I missing?
You should change this:
public class Room
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Type { get; set; }
public int BuildingId { get; set; }
}
to
public class Room
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Type { get; set; }
[ForeignKey("ContainingBuilding")]
public int BuildingId { get; set; }
public virtual Building ContainingBuilding{ get; set;}
}
This way the scaffolding will generate a select list for the building.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With