-1

I have 2 forms which performs calculations for different purposes, now I have another field in the same cshtml which is required to take the result from the above 2 forms and perform an operation in the controller. How do I achieve that. Below is my javascript which I used for forms having multiple input fields, as I said before now the issue is my 2 input fields are in 2 different forms, I need to get that and send to my controller.

The below 2 forms will perform the addition in the controller class. Now I need to consider results from the id: liability and id:totalProperty and perform another calculation at my controller.

The controller is just a post method which takes input and performs addition. Basically I need totalworth=totalProperty+liability

    <script>
    var request;
        if (window.XMLHttpRequest) {
            //New browsers.
            request = new XMLHttpRequest();
            var formData = new FormData(document.forms.assets); //here instead of forms name I want to pass //the id of the 2 input fields and send that for operation in the controller. 
        }
        if (request != null) {
            var url = "Home/TotalAssets";
            request.open("POST", url, false);
            request.send(formData)
            
        }
    
        totalAssets.value = request.response;
    }
    </script>

Below is my html

 <table align="center">
            <tr>
                
                <td>
                    $<input type="number" id="totalworth" name="totalworth" contenteditable="false"  />

                </td>
            </tr>

        </table>
<form name="property">
           
            <table>
                  
                <tr>
                    <td>  Property1  </td>
                    <td> $<input name="property1" type="number" onchange="Assets(event)" value="2000.00" /></td>

                </tr>
                <tr>
                    <td>  property2  </td>
                    <td> $<input type="number" onchange="Assets(event)" name="property2  " value="4000.00" /></td>

                </tr>
 <tr>


                    <td>$ <input type="number" readonly="readonly" name="totalProperty" id="totalProperty" onchange="Assetscalculate(event)"/></td>

                </tr>
            </table>
<form>
 <form name="liabilities">
            <table>
                <tr>
                    <td><h2>Liabilities on property</h2></td>
                </tr>
                <tr>
                    <td>
                        <h3> Short Term Liabilities</h3>
                    </td>
                </tr>
                <tr>
                    <td>  Credit Card 1  </td>
                    <td> $<input type="number" onchange="liabilityChange(event)" id="cccard1" name="cccard1" min="0" value="4342" /></td>

                </tr>
                <tr>
                    <td>  Credit Care 2  </td>
                    <td> $<input type="number" id="cccard2" name="cccard2" min="0" value="322.020"  onchange="liabilityChange(event)" /></td>

                </tr>
<tr>
                   
                    <td> $<input type="number" id="liability" name="liability" readonly="readonly"  onchange="Liabilitiescalculate(event)"  contenteditable="false" /></td>

                </tr>
        </form>

   

I think I have missed something while trying to check with your code in JS

$("#totalAssets, #liability").change(function()
        {
    let totalAssets = 0;
            let liability = 0;

    totalAssets = $('#totalAssets').val();
            liability = $('#liability').val();

            //When values are both set, POST both values to the server..
    if (totalAssets !== '' && totalAssets !== 0 && liability !== '' && liability !== 0) {
        Process(totalAssets, liability);
            }
        });

function Process(totalProperty, liability) {
    var url = '/Home/TotalAssets?totalProperty=' + totalProperty + '&liability='
        + liability;
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {
            if (xmlhttp.status == 200) {
                var result = xmlhttp.responseText;
                //Do something with the result
            }
            else {
                alert('Something went wrong: ' + xmlhttp.status);
            }
        }
    };

    xmlhttp.open("POST", url, true);
    xmlhttp.send();

} I have put above code in my javascript but it never executes the function.

  • I would use AJAX to reach your goal, check this out: https://stackoverflow.com/questions/16186083/making-a-simple-ajax-call-to-controller-in-asp-net-mvc – Peter Jul 26 '20 at 21:15
  • Yes to use the ajax as well, we need to pass the parameters right ? so I have question in passing the parameters – amritha b.a Jul 27 '20 at 12:57
  • You can add two change event handlers for both forms and when the two parameters are not null or empty you can build your own FormData object and pass it to the controller. – Peter Jul 27 '20 at 14:29
  • I got it. But in my condition I am passing the field (param1 and param2)as parameters to the controller and these fields values are dynamically created as per the result obtained in the form1 and form2. Hope my question is clear. – amritha b.a Jul 27 '20 at 14:30
  • Can you edit your question with the both needed HTML and controller? Just to be sure. – Peter Jul 27 '20 at 14:32
  • I have updated the post. – amritha b.a Jul 27 '20 at 15:21
  • It would be great if someone updates as I dont have access to chat box – amritha b.a Jul 27 '20 at 16:42

2 Answers2

0

After updating your post, it is still not entirely clear, since you have not included the JS functions and we can't guess what you additionally doing there.

I made a setup to show how I would handle the needed POST on the server, with jQuery/AJAX.

Include jQuery in your application.
First of all, you'll have to include jQuery in your application, you can do this application wide by doing this in your _Layout.cshtml, between de tags.

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

More info about including jQuery can be found here: https://www.w3schools.com/jquery/jquery_get_started.asp

Your HTML I left almost untouched, only notice that I did not include your '#totalProperty 'and '#liability' onchange events, if you did something additional you have to add it again.

HTML

<table align="center">
  <tr>
      <td>$<input contenteditable="false" id="totalworth" name="totalworth" type="number"></td>
  </tr>
</table>

<form id="property" name="property">
    <table>
      <tr>
          <td>Property1</td>
          <td>$<input name="property1" onchange="Assets(event)" type="number" value="2000.00"></td>
      </tr>
      <tr>
          <td>property2</td>
          <td>$<input name="property2" onchange="Assets(event)" type="number" value="4000.00"></td>
      </tr>
      <tr>
        <td>$ <input id="totalProperty" name="totalProperty" readonly="readonly" type="number"></td>
      </tr>
    </table>
</form>
<form id="liabilities" name="liabilities">
  <table>
      <tr>
          <td>
              <h2>Liabilities on property</h2>
          </td>
      </tr>
      <tr>
          <td>
              <h3>Short Term Liabilities</h3>
          </td>
      </tr>
      <tr>
          <td>Credit Card 1</td>
          <td>$<input id="cccard1" min="0" name="cccard1" onchange="liabilityChange(event)" type="number" value="4342"></td>
      </tr>
      <tr>
          <td>Credit Care 2</td>
          <td>$<input id="cccard2" min="0" name="cccard2" onchange="liabilityChange(event)" type="number" value="322.020"></td>
      </tr>
      <tr>
          <td>$<input contenteditable="false" id="liability" name="liability" readonly="readonly" type="number"></td>
      </tr>
  </table>

JS (depended on jQuery)

<script>
        //This part will trigger always when one of both inputs are changed..
        $("#totalProperty, #liability").change(function()
        {
            let totalProperty = 0;
            let liability = 0;

            totalProperty = $('#totalProperty').val();
            liability = $('#liability').val();

            //When values are both set, POST both values to the server..
            if (totalProperty !== '' && totalProperty !== 0 && liability !== '' && liability !== 0) {
                Process(totalProperty, liability);
            }
        });

        function Process(totalProperty, liability) 
        {
           //Create JSON object and set the needed properties..
            var data = JSON.stringify({
                'totalProperty': totalProperty,
                'liability': liability
            });
            
           //Sent and handle..
            $.ajax({
                type: 'POST',
                url: '@Url.Action("TotalAssets", "Home")',
                contentType: 'application/json',
                data: data,
                success: function() {
                    alert('Success');
                },
                error: function() {
                    alert('Error');
                },
            });
        } 
 </script>

Notice that there are several ways of processing data to a controller by AJAX, a nice post about this can be found here: https://stackoverflow.com/a/8539918/4611849

Controller

When this is done, change controller to something like this:

[HttpPost]
public ActionResult TotalAssets(string totalProperty, string liability)
{
   return Json("Your result here", JsonRequestBehavior.AllowGet);
}

Cast the variables to decimal and do the needed stuff and return the value as string, decimal or JSON, whatever you want.

Handle response
Then modify the success function in the JS function.

//Sent and handle..
$.ajax({
 type: 'POST',
 url: '@Url.Action("TotalAssets", "Home")',
 contentType: 'application/json',
 data: data,
 success: function() {
   if (response.success) 
    {
        alert(request.response);
    } 
    else {
        alert('Look into it again..');
    }     
 },
error: function() {
   alert('Error');
},
});

JS (non-depended on jQuery)
In case you want to skip the jQuery part, you can do it with plain JS as well.

    document.getElementById("totalProperty").onchange = function() 
    { 
        PreProcess();
    }

    document.getElementById("liability").onchange = function() 
    { 
        PreProcess();
    }

    function PreProcess()
    {
        let totalProperty = 0;
        let liability = 0;

        totalProperty = document.getElementById("totalProperty").value;
        liability = document.getElementById("liability").value;

        //When values are both set, POST both values to the server..
        if (totalProperty !== '' && totalProperty !== 0 && liability !== '' && liability !== 0) {
            Process(totalProperty, liability);
        }
    }

function Process(totalProperty, liability) 
{
var url = '/Home/TotalAssets?totalProperty=' + totalProperty + '&liability=' 
 + liability;
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE) { 
       if (xmlhttp.status == 200) {
           var result = xmlhttp.responseText;
           //Do something with the result
       }
       else {
           alert('Something went wrong: ' + xmlhttp.status);
       }
    }
};

xmlhttp.open("POST", url, true);
xmlhttp.send();
} 

Cheers!

Peter
  • 314
  • 1
  • 11
  • Thanks and its wonderful to see such a detailed explanation. But I am not supposed to use JQuery and needs to be done by javascript. How do I go about this? – amritha b.a Jul 27 '20 at 19:44
  • I have changed the answer! – Peter Jul 27 '20 at 21:47
  • var url = '/Home/TotalAssets?totalProperty=' + totalProperty + '&liability=' + liability; will actually navigate to a different page sending totalproperty and liability as parameters in the url right ? For me Total assets is also present in the same page where the totalproperty(form1) and liability (form2) is present – amritha b.a Jul 27 '20 at 23:57
  • its like 2 tables consisting of totalProperty and liability. And another table in the same page with totalassets. – amritha b.a Jul 27 '20 at 23:58
  • The URL will go to Home controller and TotalAssets action posting the totalProperty and Liability params. – Peter Jul 28 '20 at 06:44
  • I used your code to check but when I debug on the page load the function never executes, also when the totalproperty and liability changes the function never triggers – amritha b.a Jul 28 '20 at 13:39
  • Can you open (Chrome) Developer tools and check if there are console errors? If not open network tab and check what calls are done / check if you don't receive 404/500 error's. If you don't notice any call at all, add a breakpoint in the javascript from for example Chrome source tab. Let me know if you can find something. – Peter Jul 28 '20 at 14:21
  • I checked in the developer tools, it say that in the line $("#totalAssets, #liability").change(function(). Uncaught reference error, $ is not defined and change is not a function – amritha b.a Jul 28 '20 at 14:34
  • Yes, $ = jQuery, I have changed the answer, see the plain JS script instead of jQuery event listener, see JS (non-depended on jQuery) part. – Peter Jul 28 '20 at 14:47
  • Yes I have checked the JS part of code but finiding error over document.getElementById("totalProperty").onchange = function() { PreProcess(); } When checked it throws the error "Uncaught Type error:cannot set property 'onchange' of null. I feel this is getting called before my page load and are not able to reach DOM elements. – amritha b.a Jul 28 '20 at 15:06
  • If you add the scripts in cshtml between script tags,it should work. I tested in jsfiddle.net – Peter Jul 28 '20 at 15:20
  • I have also put under script tags. But onload of the page "totalProperty" and "liability" gets updated on its addition . Not sure why its not working – amritha b.a Jul 28 '20 at 15:45
  • I think for you its working because you are inputting the "totalProperty" or "liability" values so onchange works then but in my case "totalProperty" updates based on the values changed in the form. – amritha b.a Jul 28 '20 at 15:50
  • And my "totalProperty" and "liability" are not editable fields which just gets updated on its respective form data addition result. On change of any of the form data property fields "totalProperty" or "liability" updates the result and this should inturn change the result of my Total assets which is my end goal – amritha b.a Jul 28 '20 at 16:07
  • Do you still have those functions? : Assetscalculate(event) and Liabilitiescalculate(event), those are working right? If yes, call PreProcess(); in both. – Peter Jul 28 '20 at 16:24
  • I called the PreProcess function from both the methods which changes based on any event change and I returned the response result to the "total assets" – amritha b.a Jul 28 '20 at 16:58
  • So it's all working great? Great job. Can you mark the answer as answered to close this topic and help others out? – Peter Jul 28 '20 at 18:27
  • Sure Rymo. Thanks again – amritha b.a Jul 28 '20 at 18:34
  • You can upvote my answer by the way! Have a great day! :) – Peter Jul 28 '20 at 19:07
-1

My html remains unchanged. Where ever forms has onchange JS function, like in this case I have 2 forms, hence I have 2 onchange functions which performs calculation. With in these forms PreProcess(); is called, which inturn calls Process(totalProperty, liability) ; The request with the parameters are sent to the controller (HttpsPost) and JSON response is captured and sent to the totalAssets id. This gives me the expected result.