How to edit multiple models in a single Razor View

后端 未结 3 1749
小鲜肉
小鲜肉 2020-12-01 11:51

I am new to MVC3, I have an multiple models like BussinessDetails,ContactPerson,ServiceArea,Address and many more models.

3条回答
  •  盖世英雄少女心
    2020-12-01 12:01

    You need to include the other ViewModels into a main CompositeModel like so

    public class CompositeModel {
        public Album AlbumModel { get; set; }
        public Another AnotherModel { get; set; }
        public Other EvenMore { get; set; }
    }
    

    Send that to your view like so

    public ActionResult Index() {
        var compositeModel = new CompositeModel();
        compositeModel.Album = new AlbumModel();
        compositeModel.OtherModel = new AnotherModel();
        compositeModel.EvenMore = new Other();        
        return View(compositeModel)
    }
    

    Modify your view to take the new model type

    @model CompositeModel
    

    To refer to properties of the sub-models you can use syntax like this

    @Html.TextBoxFor(model => model.Album.ArtistName)
    

    or you can create a view in the EditorTemplates folder that takes a sub-model like AlbumModel and use EditorFor like this

    @Html.EditorFor(model => model.Album)
    

    The template would look something like this

    @model AlbumModel
    
    @Html.TextBoxFor(model => model.AlbumName)
    @Html.TextBoxFor(model => model.YearReleased)
    @Html.TextBoxFor(model => model.ArtistName)
    

    Now just post CompositeModel back to your controller and then save all the sub-models and now Bob's your uncle!

    [HttpPost]
    public ActionResult Index(CompositModel model) {
        // save all models
        // model.Album has all the AlbumModel properties
        // model.Another has the AnotherModel properties
        // model.EvenMore has the properties of Other
    }
    

提交回复
热议问题