0

I want to deliver content from different queries to the view from a single controller action method.

Currently, I have controller and I fire two queries on same table, first take students who are in 8 std and second who are in 9 std:

public class StudentController : Controller
{
    private MyDatabase db = new MyDatabase();

    public ActionResult Index()
    {
        var query = db.table1.where(t => t.Class_ID == 8);
        var query2 = db.table1.where(t => t.Class_ID == 9);
        return View(query1, query2));
    }
}

Then I want to display query1 and query2 data on a Index view of Student controller. Please help me. Thanking for all replies

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • possible duplicate of [ASP.NET MVC - View with multiple models](http://stackoverflow.com/questions/944334/asp-net-mvc-view-with-multiple-models) – AliRıza Adıyahşi Jan 04 '14 at 10:01

3 Answers3

3

You could use a view model:

public class MyViewModel
{
    public Model1 Model1 { get; set; }
    public Model2 Model2 { get; set; }
}

and then have your controller action build and pass this view model to the view:

var model1 = (from r in db.content...)
var model2 = (from r in db.content...)
var viewModel = new ViewModel();
viewModel.Model1 = model1;
viewModel.Model2 = model2;
return View(viewModel);

Now your view will be strongly typed to the view model:

@model MyViewModel

and you will be able to access its properties:

@Model.Model1.SomePropertyOfTheFirstModel
@Model.Model2.SomePropertyOfTheSecondModel
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

Create class that names ViewModels with two properties, like this:

public class ViewModels<T1, T2> {
    public T1 Model1 { get; set; }
    public T2 Model2 { get; set; }
}

In your controller create instance of ViewModels and pass it to the view:

var viewModels= new ViewModels<Model1, Model2>() { Model1 = model1, Model2 = model2 };
return View(viewModels);

Now on the view use:

@model ViewModels<Model1, Model2>
@Model.Model1.PropertyOfModel1
@Model.Model2.PropertyOfModel2
Zilberman Rafael
  • 1,341
  • 2
  • 14
  • 45
0

create a new ViewModel class which will have your data required for that view,populate that ViewModel object by data and pass it on to View

example

public class CustomViewModel
{
  //member of type model1
  //member of type model2
}
Cris
  • 12,799
  • 5
  • 35
  • 50