Using multiple models in tabs with Razor Pages Viewcomponent .Net Core 2.1 c# entity-framework-core razor


I have a slightly more complex requirement than your average single Viewcomponent that I'm trying to solve for.

I've built a web app with Razor Pages using .Net Core 2.1 and Entity Framework

On one of the pages I have a tabbed view that I use to input and display information in various formats, I've built each "tab" as an individual razor page for now as they all use multiple models, one to display and one to capture data. I've tried using partial views without any luck as when I try change the tab the whole page reloads, not ideal and quite a bit slower.

Enter Viewcomponents, I can get a simple viewcomponent that consumes one model to work fine, but for the other tabs where I have 2-3 models injected/bound I cannot seem to find a way of implementing this. Am I asking too much of the framework?

NB. I'm trying to do this using only razor pages with CSharp and no Javascript. Is this even possible or should I throw in the towel and just move to Angular-MVC?

11/13/2018 2:33:02 PM

Accepted Answer

There's a few options available to you. Your best path forward, honestly, is a wrapper class, essentially a model of models, if you will. You simply create a class with properties on it for each of the individual models you actually need. This then allows you to use this as the model for your page, but still access all your individual models for the tabs.

View components are a valid approach, but there's two things you should realize:

  1. View component rendering is entirely self-contained. In other words, your main action/view turns into basically a stub, not really doing anything on its own. Instead, all the logic for building your model and passing it to the view for each tab is contained in the view component corresponding to that tab.

  2. View components are just about rendering HTML to a page. You cannot post to a view component. You'd still be posting to your actual main action, so that would need to be setup to handle whatever the tab in question is doing.

Finally, you're at least going to need JavaScript for your tab interface, if you don't want to roundtrip to the server each time you change tabs. Tab switching while staying put is dynamic functionality that is only possible with JavaScript.

11/13/2018 2:17:22 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow