0

Is it possible to scaffold more then one class in MVC 5? I have 2 classes I'd like to been able to edit/create on one page. Do I have to scaffold separately each class and then connect somehow their views or is there a better way? Let say I have classes Office and Contacts and want Office data and Contacts for that office to be editable on one page. Also I do code first approach and not sure how to connect them with foreign key? One office can have many contacts. I have classes as below thanks

public class Office
    {
        [Key]
        public int Id { get; set; }
        public int ContactId { get; set; }
        public string OfficeName { get; set; }
    }

    public class Contact
    {
        [Key]
        public int Id { get; set; }
        public int OfficeId { get; set; }
        public string Name { get; set; }
        public string Phone { get; set; }
    }
motif
  • 35
  • 1
  • 2
  • 5
  • ^Why do people leave these comments?^ Regardless of the question, this is just an insulting comment. It's also sarcastic and totally pointless. By the way, @BobG, I followed your "instructions" and this page was the first Google result. – KidBilly Nov 14 '18 at 19:34

1 Answers1

1

It sounds like this would be a good time to use a View Model. Scaffolding is a great way to quickly create views for a given model, but at some point you've got to introduce more robust models to handle scenarios like what you've described. Create another model class (or 'view model' class if you've delegated a folder for those) such as

namespace MyProject.Web.ViewModels
{
   public class OfficeContactsVModel
   {
       public Office OfficeModel { get; set; }
       public Contact ContactModel { get; set; }
   }
}

Of course, if you are using repository pattern it'll have to be hooked up differently. You could also specify a custom model with values you need for your form and map them to a specific model in a post ActionResult in the controller. There are plenty of ways to achieve what you are looking for. (Also see: Multiple models in a view and ASP.NET MVC 5 - Scaffolding for Many to One Relationship)

Community
  • 1
  • 1
sukotto1
  • 190
  • 9