0

I am new to c# so please excuse the dumb question. I am creating a webapp using asp.net mvc. on the nav bar I have a button that brings up a modal containing a form. Now this is all done in the _Layouts.cshtml shared view. To capture the form post I use a ViewsModel which then passes it to the controller for processing. The problem is now that this loads that model into every view that is loaded in the webapp unless I use a separate shared view. Now this stops me from passing a model from the controller back to the view.

At the moment I have created a model named MasterViewModel which has the other view models as properties, but this still stops me from passing models to view...

Does anyone have any advise on how to get around this problem?

Hennericho
  • 23
  • 4

1 Answers1

0

Yes! You certainly can!

There are many ways however there are 2 that I fancy the most.

1.) The ViewBag

with this one it is simple, you can simply set the view bag in your controller to be something along the lines of Viewbag.Example = YourViewModelHere

then access it on the view by saying @Viewbag.Example.Attribute

2.) The Partial View

Another good way is to keep your architecture organized nicely and just have one view model per view. (I prefer this method)

This way you can stick to the way that you have been already handing a single view model to a single page. For some reason I tend to use this way the most, but one is not necessarily better than the other. It is more of a preference in the end.

3.) A Wrapper class

Wrap your view models in a parent class and pass the parrent class in as the view model. This will allow you to access those individual view models such as saying:

@Model.ViewModelA
@Model.ViewModelB

For individual examples of the different ways check out this post. It helped me when I was in your shoes: https://stackoverflow.com/a/4765113/5874935

Travis Tubbs
  • 827
  • 1
  • 14
  • 32
  • 1
    The `ViewBag` approach should be discouraged. You're losing strong-typing that way. A partial view doesn't really solve the issue at all, so I'm not sure where you're going with that, unless what you're actually talking about is a child action (which usually uses a partial view). Really the best approaches are either 1) a wrapper class that includes both, so you can then pass an instance of that wrapper instead and get two for one or 2) a child action. – Chris Pratt Jul 25 '17 at 17:03
  • I didn't event think of that wrapper approach! And I agree with you on the view bag part, It is kind of the lazy way to do it. However, with the partial view thing, what I am saying is to not use more than one view model per view. Which often times cramming everything into one view isn't the right choice. decomposing into multiple views with their own view bags is sometimes a better (sometimes). – Travis Tubbs Jul 25 '17 at 17:26