Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC, create View method that would return multiple objects to the view

Is there a way to create a View() method that would return multiple objects, for example, I would like to call it something like this:

public class HomeController : Controller
{
  public ActionResult Index()
  {
    return View(CustomObject1 customObject1, CustomObject2 customObject2);
  }
}
like image 815
Александар Пламенац Avatar asked Dec 29 '15 11:12

Александар Пламенац


People also ask

Can we bind multiple models to view?

There is no typecasting needed in case of ViewBag . So we can take help of ViewBag to pass multiple data from controller to View. ViewBag is a property of ControllerBase class. View Bag scope is only during the current request.

What is multiple view support in MVC?

ASP.NET MVC supports the ability to define "partial view" templates that can be used to encapsulate view rendering logic for a sub-portion of a page. "Partials" provide a useful way to define view rendering logic once, and then re-use it in multiple places across an application.


Video Answer


1 Answers

Yes, it's possible, just create a view model:

public class MyViewModel
{
    public CustomObject1 CustomObject1 { get; set; }
    public CustomObject2 CustomObject2 { get; set; }
}

which you will pass to the view:

public ActionResult Index()
{
    var model = new MyViewModel();
    model.CustomObject1 = customObject1;
    model.CustomObject2 = customObject2;
    return View(model);
}

and finally make your view strongly typed to this view model:

@model MyViewModel

and access the corresponding properties when needed:

 <div>@Model.CustomObject1.FoorBar</div>
like image 102
Darin Dimitrov Avatar answered Sep 21 '22 05:09

Darin Dimitrov