Gökhan Nas
Gökhan Nas

Reputation: 45

Multiple models in razor view MVC

We are trying to make food order and deliver web application with .NET MVC and razor view. But we are having issue with using multiple models in same view page. We found some solutions for this problem but they didn't work very well with our implementations.

Basically, I am implementing restaurant owners' register system in Register.cshtml. In same view I also did registration for normal users. If check box for "restaurant owner" is checked, user must enter his restaurant informations and register it using same controller. So if checkbox is checked, i need to access to Restaurant model too.

-We tried using Tuple but it didn't work with foreach and MVC binding functions such as Html.DropDownList().

We also could try merging two model in one view model, but this looks so brute force way to do this and there will be too much code repeat if we use this approach for every dual model combinations we need.

Can you help us to find alternative ways to use 2 models in 1 view?

Upvotes: 1

Views: 8822

Answers (2)

ViVi
ViVi

Reputation: 4464

In simple words, you cannot access data from multiple models in your view since you specify something like this @model WebApplication88.Models.YourModel on top of each view. This view can refer data from this YourModel only.

But there is no limitation on what model/list of models you can refer to on top of each view. So add a new class YourViewModel populate it all required data you want to access in the view and pass it to the view from the controller.

Read this article for more info Multiple Models in Single View in MVC.

Also refer this code project article on handling multiple models in a single view.

Upvotes: 2

Hadee
Hadee

Reputation: 1402

First of all you can't have more than one model for view because it is against all point of MVC. So you have two options:

  1. ViewModel: Create a view model based on your mix of user and restaurant models with all properties together.

  2. add a restaurant object to your user model and populate when user is restaurant owner else keep it null.

Upvotes: 1

Related Questions