banner



How To Clean Up Refreshed Partial Views Mvc

For any browser-based application, it makes sense to load into the web folio only the content that is immediately required and avert whole-page refreshes whenever possible. Ajax engineering science and JSON makes this partial-rendering easy. It is, nonetheless, worth considering ASP.NET's own partial-rendering techniques, returning HTML. It requires less customer-logic and is quicker to implement.

In the real-world, or at least in the section of the real world that I meet every day, at that place are still enough of classic ASP.Internet Web Forms and ASP.NET MVC web sites. Past 'classic spider web sites' mean web sites where the vast majority of pages are being served entirely from the web server and fully refreshed after each postback. The total refresh of the page later a postback can be significantly slow and cumbersome for users, especially when the use of graphics of these sites is quite heavy. This is the reason why at some point Ajax and fractional rendering of pages became so popular.

Today, the Ajax approach is often taken to the limit when unmarried-page applications (SPA) are built. A unmarried-page awarding (or just a few-pages application) downloads from the web server as an empty DIV chemical element. All the remaining content is inserted dynamically later on placing boosted HTTP requests for JSON information. In this context, posting a form is but a JavaScript-driven asking. The response of such a asking is mostly JSON information that the local script will process as appropriate, updating the user interface. As you lot can easily appreciate, the functioning problem of the total page refresh simply doesn't be anymore.

In between SPAs and classic full folio refresh solutions, there are techniques based on plain jQuery calls to HTTP endpoints returning JSON information. Technically speaking, a jQuery solution is non that much dissimilar from anything you can do in a SPA; Withal, it is a technique that you can use simply where required and advisable but not necessarily throughout the entire solution. You can use jQuery to brand a Go request and receive JSON data. Such data is then incorporated in the current DOM via HTML templates and libraries such equally Knockout or AngularJS. You can likewise use jQuery to identify a Post asking and receive dorsum a plain ack bulletin or some JSON information.

All this is well-known and, for the almost part, it is mainstream practice today. In this article, instead, I'll talk over a different approach for partial page refreshes that is closer to what in ASP.NET Web Forms and ASP.Net MVC is notwithstanding referred to as 'partial rendering'. The thought behind partial rendering is that of placing a jQuery call, having the endpoint perform its command or query and then returning any response as pure HTML. Some SPA purists may dislike this arroyo because-they may say-returning HTML is less efficient than returning plain JSON data. True, but the techniques presented in this article are a lot smoother to implement in coding scenarios where the predominant skills are server-side ASP.NET Web Forms and ASP.Internet MVC. Still a bit of JavaScript is required, but it is limited to using familiar DOM properties such as innerHTML or just a few core jQuery methods.

Setting Upwardly a Sample Project

Allow's say yous take an ASP.Internet MVC project with a Razor view that produces the output of Figure i. The folio contains a list of information elements that users can delete one by one past clicking a button. In classic ASP.NET, yous may have a HTML class all around the list and each of the delete buttons is implemented as a submit button. When whatever button is clicked, the folio posts back. On the server you figure out which button was clicked, and from there you lot get the ID of the element to delete.

2118-clip_image002.jpg

Here's some code that illustrates the behavior of the ASP.Internet MVC endpoint reached when whatever of the buttons in Effigy 1 are clicked.

The method DeletePost proceeds with the backend operation and then redirects to the method in charge of refreshing the view. This is an instance of the Post-Redirect-Go (PRG) pattern that keeps commands singled-out from queries and also avoids the nasty trouble of resending Post information when the user hits F5 from the browser. Hither'due south some sample lawmaking for the Index method.

The Index method gets the updated listing of customers (after the deletion) and refreshes the page. When the PRG design is used to implement a Mail, the terminal activeness repeatable by the browser is ever a GET. As a result, users volition see the updated list of customers. Even if they press F5 or Refresh inside the browser all they obtain is a obviously refresh of the folio; no additional deletion of data occurs.

How tin this code exist improved to avert a full page refresh without rewriting the entire application, or big portions of it, as a SPA? A possible arroyo is based on the HTML Message pattern-one of the nearly popular Ajax patterns. The HTML Message design refers to a situation in which the request carries back ready-to-brandish markup instead of raw (JSON) data.

The PartialView Method

In ASP.Net MVC, a fractional view is analogous to user controls in ASP.NET Spider web Forms. A partial view is a chunk of HTML that can be safely inserted into an existing DOM. About normally, partial views are used to componentize Razor views and make them easier to build and update. Partial views can also exist returned directly from controller methods. In this case, the browser notwithstanding receives text/html content but not necessarily HTML content that makes up an entire page. As a upshot, if a URL that returns a fractional view is directly invoked from the address bar of a browser, an incomplete page may be displayed. This may be something like a page that misses championship, script and style sheets. All the same, when the same URL is invoked via script, and the response is used to insert HTML inside the existing DOM, and then the net result for the end user may be much better and nicer.

With an eye on Effigy 1, let's run into what we could practice to have users click a delete push button and update the listing of customers without spinning a full page refresh.

The about of import bespeak to retrieve is that an endpoint that returns a partial HTML view should simply be called via script. The list of customers of Figure 1, therefore, might exist generated from lawmaking equally below. By the way, the sample lawmaking beneath is based on Bootstrap.

Clicking the button triggers a JavaScript function. The JavaScript role receives the ID of the client the user intends to delete and calls the appropriate controller method. When the remote call returns the script grabs the HTML clamper and updates the DIV element container of the customer list.

On the server side, the Delete method on the controller grade becomes as shown below:

To brand the actual behavior of the method clear to occasional readers of the code from the kickoff, you can also change the return blazon of the controller method from a generic ActionResult to a more specific PartialViewResult type. The actual behavior doesn't alter; simply the code is inherently easier to empathise.

Let's review the new mechanics of the page. When users click to delete a record, a POST request is made to a HTTP endpoint within a controller. The controller deletes the record and returns a clamper of HTML for the script to use and update the current DOM. The request is sent over every bit a Mail service, but at the end of the twenty-four hour period there's no strict requirement for a Mail service verb; a Become would work anyhow. At the same time, considering the request is expected to cause a country modify on the server side, it's ideally configured to be a Mail. The request is placed using JavaScript and it's not tracked by the browser. Whether it goes as a GET or POST, it won't be repeatable if the user hits F5. For the end user, the internet result is that changes become immediately visible without any page flickering.

Limitations of this Technique

The amount of script lawmaking used for this technique is the blank minimum. This is good and bad news at the same time. It'due south good considering any line of code is under your strict control: it's all nearly jQuery, the DOM and yous. It'due south bad because dependencies between controller, Razor view and JavaScript code are explicit. If you happen to change, say, the ID of the DIV in the Razor view you lot may interruption the script. Besides, if y'all modify the script or the code in the controller you may cause unexpected results in the HTML beingness served to the user. In a nutshell, the three elements (controller, Razor view, script code) must work together in perfect harmony.

There's another drawback, however, in the technique discussed so far. To run into what it is, have a await at Figure two.

2118-clip_image004.jpg

The drop-downwards menu in the effigy has 1 detail for each customer in the list. This means that when the user clicks a button to delete a customer from the customer-side, it is not enough to refresh the list. Also the contents of the drop-down should be updated. This is not an issue, instead, if the unabridged folio is rebuilt on the server as during a archetype postback and a full page refresh. Likewise, this is not an issue if you are in the context of SPA. In this instance, the asking brings back raw JSON data that the customer-side logic knows how to handle to update all the involved segments of the user interface.

More in general, whenever you send a request via JavaScript multiple segments of the user interface may be touched past the effects of that request. And when the request is coded to render prepare-to-display markup, multiple chunks of HTML should be returned. Permit'south see how to do this.

Combining Multiple Partial Views Together

The idea therefore is that a controller method (say, Delete) is invoked via JavaScript and returns multiple partial views. By blueprint, a controller method must return a type derived from ActionResult but none of the predefined activity effect types supports multiple HTML chunks. Hence, a new activity result type is in order.

The constructor of the MultipleViewResult blazon accepts a list of PartialViewResult types and caches them internally in a read-only collection. An action issue type must necessarily override the ExecuteResult method declared equally abstract in the base class. ASP.NET MVC requires that an implementation of ExecuteResult simply writes down whatever response to the output stream.

Considering MultipleViewResult contains multiple instances of PartialViewResult, it is sufficient to loop over the drove of PartialViewResult objects and ask each to execute. Finally, a separator must be added so that on the client side the various chunks tin can be easily detected. In principle, you lot tin utilise any graphic symbol (or combination thereof) to separate HTML chunks. In do, instead, any character, or combination of characters, that is common in the HTML torso can intermission the script. I unremarkably employ a cord like "—|||—", only feel costless to adapt it to your own purposes. With the MultipleViewResult class in place, hither's how to rewrite the controller method:

In the example, the two partial views use the same view model. This is not a limitation though. The script lawmaking in the client page receives a unmarried string and unpacks it before display.

Look at Effigy 2 over again and imagine a user that clicks on the selected customer. Figure 3 shows the terminal effect. The client 435 has been removed from the backend database and the view has been updated instantaneously and without total page refresh. For the user, it is definitely a nifty feel.

2118-clip_image006.jpg

Summary

Pages that are quick to respond to users are essential these days. This requirement is backside the huge success of unmarried-page applications and frameworks such as AngularJS. Building a SPA, though, may be hard not so much for the technologies involved, simply because of the skills required to build SPAs finer. The approach presented in this article represents a quick-and-piece of cake mode to extend existing ASP.Internet MVC applications and make them as responsive as SPAs without learning a make new framework.

In terms of performance it'south undeniable that downloading raw JSON is faster than downloading HTML chunks. However, plain download of HTML chunks is fast enough compared to full page refresh for the vast majority of users.

Source: https://www.red-gate.com/simple-talk/development/dotnet-development/revisiting-partial-view-rendering-in-asp-net-mvc/

Posted by: hodgewelain.blogspot.com

0 Response to "How To Clean Up Refreshed Partial Views Mvc"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel