Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
215 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...