ASP MVC 3 Two Models in One View

回眸只為那壹抹淺笑 提交于 2019-12-06 14:55:43

I think what you want is something more like this:

public class ParentModelView
{
    public IEnumerable<Model1> Model1 { get; set; }
    public IEnumerable<Model2> Model2 { get; set; }
}

And in your view

@model ParentModelView

@{
    WebGrid gridModel1 = new WebGrid(Model.Model1);
    WebGrid gridModel2 = new WebGrid(Model.Model2);
}

EDIT;

Apparently, you aren't populating the parent model correctly. I assumed you would understand how to do that.

public ActionResult MyAction() {
    var model1 = // get rows of model1
    var model2 = // get rows of model2

    return View("myview", new ParentModelView { Model1 = model1, Model2 = model2 }) ;
}

You can always use ViewModel in this case. For example create a viewmodel

public class ViewModel{

    public int Table1Column1 { get; set; }
    public string Table1Column2 { get; set; }
    public string Table1Column3 { get; set; }


    public int Table2Column1 { get; set; }
    public int Table2Column2 { get; set; }
    public string Table2Column3  { get; set; }
    public string Table2Column4 { get; set; }

}

Get the data into ViewModel from both the models in business layer or data access layer.

P.S: What McGarnagle said is true but it's vice versa, you are sending child models into the view while it is expecting ParentModelView. If you can post parts of code for controller and view, it would be helpful.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!