How to use partial views in asp.net razor-pages properly? - c#

I'm currently working on asp.net core mvc project. There is a main page (cshtml), which contains some data and two partial views in it.
Controller of this page contains action, which returns model to the view (With model binding). I've guessed that 2 more actions in the controller created to return data to both partial views would work just fine. But now my application is not working, because it is trying to pass data from main page to the partial views, creating a binding error (Partial views both has their unique models).
I'm currently using <partial> tag to add my partial views to the main view. This tag contains a property view-data which would resolve the problem with model binding. But it feels like creating a big union object with a lot of sub-objects to pass it through view-data wont be a good practice.
So i'd like to have an opinions on best practices with handling this kind of cases. What is the best way to create pages with multiple separated data like this?
My current opinion is that the best way is to make main view get viable information from the controller and in partial views make it through ajax. But anyway, there is still a question how to bypass this error with the application trying to pass data from main view to partial view (Like if i want to keep model binding in partial view to fill it with ajax).

So after some research i came to the conclusion and found a solution for my problem. PartialViews is not made for such cases. PartialView always depends on model information coming from its parent View.
Instead, if you want to achieve the same kind of behavior as i do you should use ViewComponents. It is completely independent tool which has an ability to make its own data access and build whatever model it needs. You also can access ViewComponent anywhere in your views even layouts, and even pass parameters to it by name.
I hope anyone finds this article helpful. Here is official guide by msdn on how to implement and use view components

Related

ASP.NET Core specific way to reuse Edit and New view content in cshtml

I have a New and Edit view that basically contain duplicate cshtml. What's the most efficient way to refactor so I can stay DRY?
I already looked through Stack Overflow, and all the answers I could find were for .NET Framework. I wanted to see if there are more efficient ways to reuse code now, with ASP.NET Core.
Is using a Partial View or a View Component the most efficient method? Or is there another ASP.NET Core specific way to handle this?
Partial Views and View Components both allow you to centralize your views, and in that regard are interchangeable. Partial Views, however, exclusively contain view information (i.e., a cshtml file). By contrast, View Components additionally allow you to define preprocessing logic (similar to an [HttpGet] controller action).
Data Access and Parameterization
It's important to note that both Partial Views and View Components can have arguments or values passed into them.
In a Partial View, this is done by relaying either a ViewDataDictionary or a custom view model to the Partial View (reference); this can be done using either the PartialAsync() HTML Helper or by using the <partial /> tag helper's model or view-data attributes.
In a View Component, this is done by defining parameters on the InvokeAsync() method, and then relaying those as either an anonymous object via the InvokeAsync() HTML Helper or as attributes on the <vc:[view-component-name] /> tag helper.
As a result, both approaches can be parameterized and/or data bound, thus allowing them to be respond to the current state.
View Component Specific Capabilities
Where View Components distinguishes themselves is in that ability to define preprocessing logic via the InvokeAsync() method before returning a view model to the view, potentially including access to classes registered via dependency injection (e.g., via a composition root or a dependency injection container).
This is especially useful if your view needs to access data that's not (conveniently) available in the parent view—e.g., via a dependency, a database, or a webservice. So, for instance, if your view component is used by dozens of different views, but always needs access to similar data, this can allow you to centralize that logic so you don't need to look it up in each controller.
Examples: Given the ability to lookup data as part of a view component, I frequently use them for site navigation. That way, I don't need to lookup the navigation data in every single [HttpGet] action, nor include it in every single view model; it can be self-contained. Similarly, I use it for views containing common lookup data, such as dropdown boxes bound to data retrieved from an API or database call.
The Most Efficient Method
As far as which is most "efficient", that is a fairly subjective question, and not one we can answer without more information about your use case.
If a Partial View satisfies your needs, however, it is certainly the simplest and easiest approach: A View Component necessitates that an additional class be created and registered in order to support your view.
The question here, though, is likely less about efficiency and more about your requirements. If your view needs additional preprocessing to e.g. modify the view data, construct a new view model, or collect additional data, then you should use a View Component; otherwise, prefer a Partial View.
That said, given that you're looking to centralize the markup between a New and Edit view, I would expect a Partial View to satisfy your requirement. Both views will likely share an existing view and binding model, and the data populated will be specific to each view, therefore there likely isn't much need to centralize any pre-processing logic.
The one potential exception is if your New and Edit forms include lookup data—such as dropdown lists—sourced from a database. That said, as these views are almost certainly being returned from the same controller, you can easily centralize the lookup of that data in the controller itself, without needing to rely on a View Component to do that for you.
The best way to go about it is to use partial views!
https://learn.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-6.0

Best way to split huge view model/xaml

I’m refactoring a big view model and it's associated XAML page. I use Prism. The main page has a clear functionality, create an avatar. There are steps to create the avatar like take the picture, edit the picture, etc. I have now a detail side bar which controls the navigation for the steps and a main content area which I show different content depending on these steps. I hide/show the appropriate views depending on the step. The project grew and now I have a 2000+ line view model and a huge XAML file.
What I ended up doing after some research is creating ContentViews for each step (showing and hiding them for each step again), so the XAML get's modularized for each step and also a View Model for each step. I was successful in binding the ContentView to each ViewModel but now I have problems communicating the different View Models information.
As before everything was in the same View Model, all views could share the same bound properties if needed. Now, as each view model is independent I need to find a way to properly share this information. My first approach was to use the Messaging Center. This way I can send the information i need to share to the view model that manages the navigation between steps (NavigationViewModel) and this can send this information to the following view models.
The thing is that I don't really like this solution as I find it too complex and will end up with a lot of code in the NavigationViewModel to subscribe/send to each sub-viewmodel to pass the shared information.
So my question is, do you know any other way to ease the communication between the view models?
I even thought about using partial classes to 'hide' my big view model complexity, but I think this is not a good idea.
Recenlty i came across the same problem,my ViewModel became really huge(with hundreds of properties) .So what i did is :
Created an Interface class.Putting all the common properties in there.Let's say IA.
Created another class inheriting IA.
And now multiple classes are inherting IA,reducing the overall properties numbers.

asp.net mvc - how can I have multiple viewmodels bound to a view [duplicate]

This question already has answers here:
Multiple models in a view
(12 answers)
Closed 5 years ago.
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?
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

Can I use the model from an MVC partial view in my Knockout viewmodel in the main view?

I am currently working on a view that has several partial views within in, which might also have partial views in them.
I have set up a Knockout viewmodel for the entire view, which also covers the partial views. This is in a separate js file. I have set it up as one viewmodel as I will want to save it all as a whole. Maybe this is the wrong way to go about it and I should have different viewmodels for the different views.
The partial views have their own view models, which I want to use to populate the knockout viewmodel.
I have only been using Knockout for a few months, so I am not sure if this is possible or sensible. I would greatly appreciate any opinions or examples of how to do this, or any alternatives, e.g. should I used a separate knockout viewmodel for each partial and then post all back to the server as separate ajax?
Many thanks in advance.
you can use knockout component to get your particular html and js file. Using knockout components you will be able to separate your concerns entirely with the help of knockoutjs.
Lastly if you want to have more manageable Web Application you can use durandal that work great using knockoutJs, jQuery and bootstrap.

ASP.NET MVC - Single view for Edit and Read only?

We have a situation where we need a read only version of an edit page. This is permission based as well as based on the status of the object. My thought is to separate this out into a completely new view but the other opinions are to place this logic in the edit view.
Some information about how the view is structured:
Form elements
Editor templates
Partial views
Kendo controls (fluent wrappers)
So in order to complete the task at hand means the read only functionality needs to exist in multiple places and must be passed to editor templates / partial views by view data.
There is also HTML helpers / extensions that are being used on the page which means updating these too.
Lastly, with the Kendo controls, a lot of the logic of the grid (in-line editing functionality) logic exists in external JS files so we have yet another place to modify the code.
My question is what is the 'best practice' in this regard?
Do we duplicate mark-up (cshtml) by separating the read only view from the edit view.
Or do we change the edit view to accommodate the read only functionality?
It just seems like changing the edit view will add a whole lot of complexity and dependencies for such a trivial task.
You can share the single view for readonly and editable elements by using razor conditioning in the view, But it seems to complicated to manage if the view content complex processing or elements, I recommend you to use separate view and send the appropriate view from the controller's action method depends on your criteria.
You can also use Html.EditorForModel directly to render elements as per your model data annotations OR Html.DisplayForModel to render all model properties for read only purpose.

Categories

Resources