简体   繁体   中英

2sxc - Calculated vars between razor and JS on a @foreach loop

I'm creating a view with two text inputs ('est' being calculated via JS based on 'idd') on top, and then a table with a @foreach loop to display all my data. Some fields will be calculated based on each other, but others must be calculated after the page is loaded, every time the 'est' and/or 'idd' inputs change.

Since razor is calculated server side and this JS client side, how can I set these type of calculated columns like the one in this example:

This should be the myResult var (or 'est' value) + @Content.V2

I though about pulling the @Content.EntityId to set some dynamic var names like:

<input type="text" id="@Content.EntityId-newfield"">

and pulling some <script>get the myResult again, add @Content.V2, set document.getElementById('@Content.EntityId-newfield').value</script> inside the loop but it doesn't work.

How can I achieve this?

Here's the full page:

<h1>My page</h1>
<br>
idd: <input type="text" id="idd" oninput="calculate()"> __ est: <input type="text" id="est">
<br><br>
<table border="1">
    <thead>
        <tr>
            <th></th>
            <th>Id</th>
            <th>Title</th>
            <th>V1</th>
            <th>V2</th>
            <th>V1 / V2</th>
            <th>Field I know not how to calculate</th>
        </tr>
    </thead>
    <tbody>
        @foreach(var Content in AsDynamic(Data["Default"])){
        <tr>
            <td>@Edit.Toolbar(Content, actions: "edit,replace")</td>
            <td>@Content.EntityId</td>
            <td>@Content.Title</td>
            <td>@Content.V1</td>
            <td>@Content.V2</td>
            <td>@Math.Round(@Content.V1 / @Content.V2, 2)</td>
            <td>This should be the myResult var (or 'est' value) + @Content.V2</td>
        </tr>
        }
    </tbody>
</table>

<script>
    function calculate() {
        var idade = document.getElementById('idd').value;
        var myResult = (parseInt(idade) + 4) * 2;
        document.getElementById('est').value = myResult;
    }
</script>

Figure an array of functions would do the trick.

Before @foreach:

var arrayOfFunctions = [];
<input type="text" id="peso" oninput="callFunctions()">

inside @foreach:

arrayOfFunctions.push(function(setPeso) { document.getElementById('@Content.EntityId').value = setPeso * @Content.fieldToCalculate; });

after: @foreach:

function callFunctions() {
    var myPeso = parseInt(document.getElementById('peso').value);
    arrayOfFunctions.forEach(f => f(myPeso));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM