Is it possible to update a current HTML value with a dynamically calculated value using HTML, CSS, or both?

While working on generating HTML to be passed back from a REST method, I encountered the following code snippet:

StringBuilder builder = new StringBuilder();
builder.Append("<div class=\"row\">");
builder.Append("<div class=\"col-md-6\">");
builder.Append("<div class=\"bottomleft\">");
// TODO: Replace the hardcoded val ("$9,814.81") with the actual val
builder.Append("<h2 class=\"sectiontext\">Forecasted Spend - $9,814.81</h2>");

(initial HTML structure has been set up before this). Subsequently, live data is added as shown below:

builder.Append("<table>");
builder.Append("<tr>");
builder.Append("<th>Item Code</th>");
builder.Append("<th class=\"rightjustifytext\">Last Week's Usage</th>");
builder.Append("<th class=\"rightjustifytext\">This Week's Price</th>");
builder.Append("<th class=\"rightjustifytext\">Forecasted Spend</th>");
builder.Append("</tr>");

decimal forecastedSpend;
int lastWeeksUsage;
int loopCount = 0;
int totalUsage = 0;
decimal totalForecastedSpend = 0.0M;
foreach (DataRow dr in dtViewPriceMatrixVarianceResults.Rows)
{
    // Data rows are dynamically generated here
}

(The totals are calculated and added at the end) The final step involves closing the elements and returning the prepared HTML content within the StringBuilder:

builder.Append("</table>");
builder.Append("</div>");
builder.Append("</div>");
return builder.ToString();

The challenge arises when trying to replace the placeholder value "$9,814.81" with the actual figure of totalForecastedSpend, which is determined during the population of the table rows with live data. While a workaround involving storing values in a generic list and utilizing them later works, I am exploring alternative solutions using HTML or CSS. Is there a way to achieve this? Or would adopting such an approach be detrimental?

The related REST method is defined as follows:

[Route("{unit}/{begdate}/{enddate}")]
public HttpResponseMessage GetQuadrantData(string unit, string begdate, string enddate)
{
    // Implementation logic for assembling HTML content
}

Can the issue of replacing the placeholder value with the actual totalForecastedSpend be addressed through HTML/CSS manipulation, or should another strategy be pursued?

UPDATE

Although the initial question remains unresolved, implementing a solution involving pre-calculating values and storing them in a list proves to be effective:

A dedicated class is created:

public class ForecastedSpend
{
    public String ItemCode { get; set; }
    public int LastWeeksUsage { get; set; }
    public Decimal Price { get; set; }
    public Decimal ForecastedSpendCalcd { get; set; }
}

The earlier code segment is replaced with:

// Pre-calculation and storage logic using ForecastedSpend class
// Table row generation based on stored values

This revised approach successfully handles the scenario.

Answer №1

One alternative approach to manipulate a result before displaying it on the browser is by generating an XML result and utilizing a suitable XSL stylesheet for transformation.

There are various advantages to this methodology:

  • It separates format from data, which is considered a best practice.
  • It helps in reducing bandwidth, as the XSL is transmitted only once per device and then often stored locally in cache.
  • The browser carries out the transformation natively, resulting in performance comparable to direct HTML rendering.
  • It contributes to maintainability: In case of format changes, modifications are required only in the XSL stylesheet without having to touch the server endpoint program at all.

Answer №2

If you're seeking a way to change the order of elements in css/html, consider utilizing the flexible box layout.

For instance:

HTML:

<div id="mycontainer">
     <table id="mytable">
        <tr><td>row 1</td></tr>
        <tr><td>row 2</td></tr>
        <tr><td>row 3</td></tr>
        <tr><td>row 4</td></tr>
        <tr><td>row 5</td></tr>
        <tr><td>row 6</td></tr>
        <tr><td>row 7</td></tr>
    </table>
    <p id="mytotal">2000$</p>
</div>

Then, add the following CSS:

div#mycontainer {
    display: flex;
    flex-direction: column;
}
p#mytotal {
    flex: 1;
    order: 1;
}
table#mytable {
    flex: 1;
    order: 2;
}

Note that I've positioned the table at 2nd place and totals at 1st (using the order property).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Android layout featuring Ionic2 navbar with icons aligned on both sides at the top

<ion-header> <ion-navbar align-title="center" color="primary" hideBackButton> <ion-buttons ion-button icon-only start class="card-buttons"> <button class="card-buttons" (t ...

Transferring a file from one PHP script to another

I have a feature on my website where users can upload an HTML file to use as a theme. The uploaded HTML file undergoes some checks before certain options are presented to the user. After filling out the form related to the HTML file, the user submits the f ...

The error message "ReferenceError: $ is not defined" is displayed within

My current requirement involves loading templates within an iframe, and to achieve this, I have implemented the following code: <div class="col m8 l8 s12 margin-top-30" id="hue-demo-bg-div"> <iframe id="myiframe" src="/themes/{{$themeid}}.ht ...

Achieve full height in Grid component of material UI by eliminating margins

In this codesandbox example, I have successfully set the grid container height to full using 100vh. However, there is an issue with a margin of 8px being added by the user agent to the body element, and I'm struggling to find a solution to remove it. ...

Iterate through a list of items using ngFor directive in Angular, and

How can I apply an active class to the selected item in a ngFor loop without toggling it on every item? <div class="mb-2 item rounded bg-white border" *ngFor="let item of keys(); let i = index" (click)=&qu ...

Tracking the email field in a React form with refs

Hey there! I'm a music engineer working on my own personal website using React. I'm currently facing an issue with creating a contact form that allows users to input a subject in a text field, a message in a textarea, and then click a "reach out" ...

What's the best way to arrange the layout to ensure that every row contains exactly three items that are evenly spaced apart?

Struggling to figure out how to display three items in each row with even spacing using react js and bootstrap. I've been grappling with this for hours today, trying to implement grid layouts on the page. I managed to render 3-4 items on each row, bu ...

No changes were seen in CSS animation when using ng-repeat in AngularJS 1.3.1

Recently delving into the world of AngularJS and I seem to be missing something. I attempted a basic CSS animation [plunker][1] but it doesn't seem to be working. Any suggestions or assistance would be greatly appreciated. Thanks in advance! [1]: htt ...

HTML textarea fails to recognize inline styles

My journey with JHipster began recently when I embarked on my first project. Two entities were created, one of which resembles a blog. This particular blog entity has a content attribute that interacts with a textarea. In my blogs.html file, I allowed the ...

What happens in the React tutorial when the clear fix is commented out and the appearance does not change?

Currently, I am working through the React tutorial and have encountered a question regarding their starter code: class Square extends React.Component { render() { return ( <button className="square"> {/* TODO */} </butto ...

Set the background image width to 75% of the screen size

I want to use this image https://i.sstatic.net/gt30c.jpg as a background for a section on my page. My preference is to have the white part cover only 75% of the screen, stopping before reaching the content in the left grid. Is it possible to achieve this ...

Is a minimum height of 100% the right choice?

Is there a way to create a container element that automatically adjusts its size based on the content it holds, while still having specific endpoints defined by surrounding elements? To see an example of what I'm looking for, visit: I am hoping to s ...

The troubleshooting guide for resolving compatibility issues with a background video across various browsers

Something strange occurred. My background video was functioning properly on all browsers until this morning. However, it suddenly stopped working on certain browsers. The video either does not play or freezes immediately. I tried clearing my cache, rever ...

Unlock the power of VueJS with advanced checkbox toggling for array data

I have encountered an issue while working with VueJS regarding the implementation of two features for a set of checkboxes. Initially, the checkboxes are generated dynamically. I am in need of a master 'toggle' checkbox that can toggle the stat ...

Adding information to a single class that shares a common name

Currently, I have successfully implemented a row cloning scenario where multiple dynamic rows are created after confirming an inventory number from a MySQL database. However, I am facing an issue with inserting the inventory data only to the next DIV eleme ...

struggling to incorporate API Json response data into my HTML file using AngularJS

Below is the code I am currently using: angular.module('ngApp', []) .factory('authInterceptor', authInterceptor) .constant('API', 'http://myserver.com/app/api') .controller('task', taskData) function task ...

What is the best way to exclude any external CSS stylesheets from affecting a particular component within a complex project?

I am struggling to isolate the tailwind CSS in a large project. Initially, I had two products with their CSS, and later added a third product with tailwind styling. Now, I am facing issues trying to exclusively use the tailwind CSS while disregarding the ...

When an HTML element such as a div includes multiple classes, it can impact the render tree and ultimately affect the performance of the webpage

<div class="a b c d e f g h i j"> </div> In order to display a web page, the browser parses the data to create both the DOM and CSSOM trees. These two trees are then merged into a render tree, which is used to determine the layout of each visi ...

What is the most effective method for checking the structure of a JSON string object in a JAVA program

Is there a way to quickly determine if a given string object is a properly formatted JSON object, regardless of its actual data? For example: "abc":"123", "cba":"233" } This scenario should result in a format exception. { "abc":"123" "cba":"233" } Woul ...

Clickable button functionality problems in Outlook email responses

Is there a way to create a button that is fully clickable (not just the text), aligned to the left on desktop and full width on mobile, while also being compatible with Outlook? I've experimented with various types of buttons like bulletproof, bombpro ...