Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass two models to one View

I'm trying to pass two models into a single view, which are needs to populate a table.

Here I have a requirement to implement this application only using ASPX (asp.net-MVC-4). I can do the task using Razor codes but not with ASPX.

I need your kind help to complete the task

like image 527
Sandaru Avatar asked Dec 15 '14 11:12

Sandaru


People also ask

Can a view have multiple models?

Yes, you can use Tuple (brings magic in view having multiple model).

Can one view have multiple controllers?

Yes. Mention the view full path in the View method. If the name of your Views are same in both the controllers, You can keep the Common view under the Views/Shared directory and simply call the View method without any parameter. The View name should be same as the Action method name.

Why do we use partial view in MVC?

A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.

Why TempData is used in MVC?

What is TempData and How to Use in MVC? TempData is used to transfer data from the view to the controller, the controller to the view, or from an action method to another action method of the same or a different controller. TempData temporarily saves data and deletes it automatically after a value is recovered.


1 Answers

Make one class that contains both models

Your first model:

public class ModelOne { ... }

Your second model:

public class ModelTwo { ... }

The model that you pass to your view:

public class UltimateViewModel 
{
  public ModelOne One { get; set; }
  public ModelTwo Two { get; set; }
}

There is no problem with creating a view model class to encapsulate everything that you want to send to the view. In fact, this would be preferable to doing something like storing one of your models in ViewState, since you can enforce your strong typing in the view, referring to everything using @Model.One or @Model.Two`.

like image 194
Yaakov Ellis Avatar answered Sep 28 '22 17:09

Yaakov Ellis