how to create a view with multiple models mvc 4?

后端 未结 2 1258
一整个雨季
一整个雨季 2021-01-14 09:00

so i works in asp.net mvc 4 project and i have a problem in my view, what i want is create a view with 2 differnt type of model,first view (Index) take IEnumerable (Models.m

相关标签:
2条回答
  • 2021-01-14 09:34

    You just need to create a second view called Details which is strongly typed with SubscribersModel

    @model _3SDWebProject.Models.SubscribersModel
    

    Right-click anywhere in the code for your Details() action
    Select Add View...
    Leave "Details" for View name
    Check "Create a strongly-typed view"
    Select your SubscribersModel from the Model class dropdown
    Scaffold template: Details
    Click "Add"

    0 讨论(0)
  • 2021-01-14 09:53

    Create a new, compound view model that includes both of these view models.

    public class CompoundViewModel
    {
        public IEnumerable<SubscribersModel> AllSubscribers {get; set;} 
        public SubscribersModel SelectedSubscriber {get; set;}
    }
    

    Ideally also split your view into partial views and render these two part of your compound model into them using DisplayFor<> or EditorFor<>. That way you can reuse the view for a 'SubscriberModel' elsewhere in the application if you need it.

    Your controller code could also be improved by using a dependency injection framework (e.g. Autofac) to inject those dependencies that you are currently newing up.

    Another alternative, given that you are using the same model for the list and the details view, would be to handle this client-side using Javascript, either manually using jQuery or with one of the newer frameworks that allows client-side model binding like Knockout.js or Angular.js.

    0 讨论(0)
提交回复
热议问题