There are many ways to implement a function in ASP. net mvc. Today we will discuss the differences between using renderpartial and renderaction to render part of the content in the view.
For example, we want to present the content shown in the following figure.
In general, we may need to present this content on the page of the dashboard to ensure that this content can be displayed in each view using this template, in addition, the content must be combined with the specific business logic. The content is generated in the user control, so that the content can be separated from the parent page or view. We can present the content in at least two ways. Here we will only discuss the differences between the representation of renderpartial and reneraction, and consider the advantages and disadvantages of using them.
Method 1: Use the HTML. renderpartial method (the new method added by ASP. net mvc preview5)
A simple example
<% Html.RenderPartial( "SomeControl.ascx", ViewData.Model ); %>
As you can see, this method displays user controls by accepting the user control's file name and corresponding changeable data.
Let's take a look at the advantages and disadvantages of using this method.
- Advantages
- Easy to use, no action required
- Disadvantages
- You must specify the path of the user control file to render the View content.
- A view needs to provide data for another view, that is
- The view needs to undertake the task of organizing entity data, which is exactly what the business logic needs to do.
- Because the view described above provides data features, you may skip the controller and send a request directly to the service layer or even the database.
Method 2: Use the HTML. renderaction Method
Another method of rendering user control content is the same as that of rendering a view in general, that is, the Controller determines the specific user control content to be presented. The renderaction method flexibly presents a specific view, user control, or part of content through the Controller.
A simple example
<% Html.RenderAction<MyController>( x => x.ControllerAction() ); %>
- Advantages
- Let the Controller do what it should do: the organizational logic and the communication between the business logic.
- Abstract The actually used views/user controls to facilitate future reconstruction.
- Abstract The business logic in the controller, which allows your business logic to focus on what it should do.
- Use a Lambda expression with a strong type
- Disadvantages
- You must create an action to process the request.
OK, have Fan ~