locked
Controller creates new instance of Class after ButtonClick RRS feed

  • Question

  • User-462092770 posted

    I Have a simple calculator (in asp.net mvc c#) so far its starting and i can use the buttons but after every click there is a new instance of my Class.

    Do i need a Database to store the result and use it for the next interaction or is there a easier way(another way)?????

    for example if i want to type 22 it will write 2 an clear textbox and write 2. My Calculator Class works in my WebForms project just fine .

    Thursday, September 3, 2020 2:00 PM

Answers

  • User1686398519 posted

    Hi Jonny0024,

    1. there is a new instance of my Class
      • Since you did not provide some code, I cannot reproduce your problem.
    2. Do i need a Database to store the result
      • You can store the result in the database after calculating the result.
      • I make an example, you can refer to it.

    Model

        public class Calculator
        {
            [Key]
            public int Id { get; set; }
            public string CalculatorExpression { get; set; }
            public string CalculatorResult { get; set; }
        }

    HomeController

            public CalculatorDemoContext db = new CalculatorDemoContext();
            public ActionResult Index()
            {
                return View(db.Calculators.OrderByDescending(c => c.Id).Take(5).ToList());
            }
            [HttpPost]
            public ActionResult saveToDatabase(string CalculatorExpression, string CalculatorResult)
            {
                var calculator = new Calculator {CalculatorExpression=CalculatorExpression,CalculatorResult=CalculatorResult };
                db.Calculators.Add(calculator);
                db.SaveChanges();
                return PartialView("_CalculatorHistory", db.Calculators.OrderByDescending(c => c.Id).Take(5).ToList());
            }
                
    
            [HttpPost]
            public ActionResult compute(string input)
            {
                //Regular expression
                string num = @"[\-]?([0-9]{1,}\.?[0-9]*)";  //Match numbers
                string exp1 = @"(?<NUM1>" + num + ")" + @"(?<OP>[\*\/\^])" + @"(?<NUM2>" + num + ")"; //Match multiplication, division, power operation
                string exp2 = @"(?<NUM1>" + num + ")" + @"(?<OP>[\+\-])" + @"(?<NUM2>" + num + ")"; //Matching addition, addition
                //Define declaration regular expression
                Regex isExp1 = new Regex(exp1); //Multiplication, division, power operation
                Regex isExp2 = new Regex(exp2); //Addition, subtraction
                //Create matching objects
                Match mExp1, mExp2;
                //First deal with the multiplication, division, and power operations in the expression
                mExp1 = isExp1.Match(input);
                while (mExp1.Success)
                {
                    GroupCollection gc = mExp1.Groups;  //Group match
                    decimal num1 = Convert.ToDecimal(gc["NUM1"].Value);   //Take the operand NUM1
                    decimal num2 = Convert.ToDecimal(gc["NUM2"].Value);   //Take the operand NUM2
                    switch (gc["OP"].Value) //Take the operator OP and judge the operation
                    {
                        case "*":
                            num1 *= num2; break;
                        case "/":
                            if (num2 == 0)  //Determine whether the divisor is 0
                            {
                                return Json("DivNumZero", JsonRequestBehavior.AllowGet);//Returns the divisor 0 flag string
                            }
                            else
                            {
                                num1 /= num2;
                                break;
                            }
                    }
                    input = input.Replace(mExp1.Value, string.Format("{0:f2}", num1)); //Replace the calculation result into the expression
                    mExp1 = isExp1.Match(input);    //Re-match multiplication and division
                }
                //Process addition and subtraction
                mExp2 = isExp2.Match(input);
                while (mExp2.Success)
                {
                    GroupCollection gc = mExp2.Groups; 
                    decimal num1 = Convert.ToDecimal(gc["NUM1"].Value);  
                    decimal num2 = Convert.ToDecimal(gc["NUM2"].Value);   
                    switch (gc["OP"].Value) 
                    {
                        case "+": num1 += num2; break;
                        case "-": num1 -= num2; break;
                    }
                    input = input.Replace(mExp2.Value, string.Format("{0:f2}", num1));  
                    mExp2 = isExp2.Match(input);    //Rematch addition and subtraction
                }
                //Return the result 
                return Json(input,JsonRequestBehavior.AllowGet);
            }

    Index

    <h2>CalculatorDemo</h2>
    @model IEnumerable<CalculatorDemo.Models.Calculator>
    <input id="show" />
    <button id="ShowCalculatorHistory">CalculatorHistory</button>
    <input type="hidden" id="hiddenshow" />
    <table id="Calculator" class="table table-bordered">
        <tr><td class="active">delete</td><td class="active">*</td><td class="active">/</td><td class="active">=</td></tr>
        <tr><td>7</td><td>8</td><td>9</td><td class="active">C</td></tr>
        <tr><td>4</td><td>5</td><td>6</td><td class="active">-</td></tr>
        <tr><td>1</td><td>2</td><td>3</td><td class="active">+</td></tr>
        <tr><td>+/-</td><td>0</td><td>.</td><td id="result" class="active">=</td></tr>
    </table>
    <div id="CalculatorHistory" style="display:none">
        <table id="CalculatorHistoryTable" class="table table-bordered">
            <thead><tr><th>History</th></tr></thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr><td>@item.CalculatorExpression=@item.CalculatorResult</td></tr>
                }
            </tbody>
        </table>
    </div>
    @section scripts{
        <script>
            $("#Calculator").on('click', 'td', function (event) {
                $('.success').removeClass('success');
                $(this).addClass('success');
                if ($(this).html() == "C") {
                    $("#show").val('');
                } else if ($(this).html() == "delete") {
                    $("#show").val($("#show").val().substring(0, ($("#show").val().length - 1)));
                }else if ($(this).html() != "=") {
                    if ($(this).html() == "+/-") {
                        $("#show").val($("#show").val() + "-");
                    } else{
                        $("#show").val($("#show").val() + $(this).html());
                    }
                }
            });
            $('#result').click(function () {
                var calculatestring = $("#show").val();
                $("#hiddenshow").val(calculatestring);
                $.ajax({
                    url: "@Url.Action("compute")",
                    data: { input: calculatestring},
                    type: "POST",
                    success: function (data) {
                        $("#show").val(data);
                        saveToDatabase($("#hiddenshow").val(), data);
                        $('.success').removeClass('success');
                    }
                })
    
            });
            function saveToDatabase(calculatorExpression, calculatorResult){
                $.ajax({
                    url: "@Url.Action("saveToDatabase")",
                    data: { CalculatorExpression: calculatorExpression, CalculatorResult: calculatorResult },
                    type: "POST",
                    success: function (data) {
                        $("#CalculatorHistory").html(data);
                        CalculatorHistory();
                    }
                });
            }
            $('#ShowCalculatorHistory').click(function () {
                if ($("#CalculatorHistory").css('display') == 'none') {
                    $("#CalculatorHistory").show();
                } else {
                    $("#CalculatorHistory").hide();
                }
            });
            $(function () {
                CalculatorHistory();
            });
            function CalculatorHistory() {
                $("#CalculatorHistoryTable").on('click', 'tr', function (event) {
                    $('.success').removeClass('success');
                    var currenttd = $(this).find("td");
                    $("#show").val(currenttd.html().split("=")[0]);
                });
            }
        </script>
    }

    _CalculatorHistory

    @model IEnumerable<CalculatorDemo.Models.Calculator>
    <table id="CalculatorHistoryTable" class="table table-bordered">
        <thead><tr><th>History</th></tr></thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr><td>@item.CalculatorExpression=@item.CalculatorResult</td></tr>
            }
        </tbody>
    </table>

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 4, 2020 6:31 AM

All replies

  • User1686398519 posted

    Hi Jonny0024,

    1. there is a new instance of my Class
      • Since you did not provide some code, I cannot reproduce your problem.
    2. Do i need a Database to store the result
      • You can store the result in the database after calculating the result.
      • I make an example, you can refer to it.

    Model

        public class Calculator
        {
            [Key]
            public int Id { get; set; }
            public string CalculatorExpression { get; set; }
            public string CalculatorResult { get; set; }
        }

    HomeController

            public CalculatorDemoContext db = new CalculatorDemoContext();
            public ActionResult Index()
            {
                return View(db.Calculators.OrderByDescending(c => c.Id).Take(5).ToList());
            }
            [HttpPost]
            public ActionResult saveToDatabase(string CalculatorExpression, string CalculatorResult)
            {
                var calculator = new Calculator {CalculatorExpression=CalculatorExpression,CalculatorResult=CalculatorResult };
                db.Calculators.Add(calculator);
                db.SaveChanges();
                return PartialView("_CalculatorHistory", db.Calculators.OrderByDescending(c => c.Id).Take(5).ToList());
            }
                
    
            [HttpPost]
            public ActionResult compute(string input)
            {
                //Regular expression
                string num = @"[\-]?([0-9]{1,}\.?[0-9]*)";  //Match numbers
                string exp1 = @"(?<NUM1>" + num + ")" + @"(?<OP>[\*\/\^])" + @"(?<NUM2>" + num + ")"; //Match multiplication, division, power operation
                string exp2 = @"(?<NUM1>" + num + ")" + @"(?<OP>[\+\-])" + @"(?<NUM2>" + num + ")"; //Matching addition, addition
                //Define declaration regular expression
                Regex isExp1 = new Regex(exp1); //Multiplication, division, power operation
                Regex isExp2 = new Regex(exp2); //Addition, subtraction
                //Create matching objects
                Match mExp1, mExp2;
                //First deal with the multiplication, division, and power operations in the expression
                mExp1 = isExp1.Match(input);
                while (mExp1.Success)
                {
                    GroupCollection gc = mExp1.Groups;  //Group match
                    decimal num1 = Convert.ToDecimal(gc["NUM1"].Value);   //Take the operand NUM1
                    decimal num2 = Convert.ToDecimal(gc["NUM2"].Value);   //Take the operand NUM2
                    switch (gc["OP"].Value) //Take the operator OP and judge the operation
                    {
                        case "*":
                            num1 *= num2; break;
                        case "/":
                            if (num2 == 0)  //Determine whether the divisor is 0
                            {
                                return Json("DivNumZero", JsonRequestBehavior.AllowGet);//Returns the divisor 0 flag string
                            }
                            else
                            {
                                num1 /= num2;
                                break;
                            }
                    }
                    input = input.Replace(mExp1.Value, string.Format("{0:f2}", num1)); //Replace the calculation result into the expression
                    mExp1 = isExp1.Match(input);    //Re-match multiplication and division
                }
                //Process addition and subtraction
                mExp2 = isExp2.Match(input);
                while (mExp2.Success)
                {
                    GroupCollection gc = mExp2.Groups; 
                    decimal num1 = Convert.ToDecimal(gc["NUM1"].Value);  
                    decimal num2 = Convert.ToDecimal(gc["NUM2"].Value);   
                    switch (gc["OP"].Value) 
                    {
                        case "+": num1 += num2; break;
                        case "-": num1 -= num2; break;
                    }
                    input = input.Replace(mExp2.Value, string.Format("{0:f2}", num1));  
                    mExp2 = isExp2.Match(input);    //Rematch addition and subtraction
                }
                //Return the result 
                return Json(input,JsonRequestBehavior.AllowGet);
            }

    Index

    <h2>CalculatorDemo</h2>
    @model IEnumerable<CalculatorDemo.Models.Calculator>
    <input id="show" />
    <button id="ShowCalculatorHistory">CalculatorHistory</button>
    <input type="hidden" id="hiddenshow" />
    <table id="Calculator" class="table table-bordered">
        <tr><td class="active">delete</td><td class="active">*</td><td class="active">/</td><td class="active">=</td></tr>
        <tr><td>7</td><td>8</td><td>9</td><td class="active">C</td></tr>
        <tr><td>4</td><td>5</td><td>6</td><td class="active">-</td></tr>
        <tr><td>1</td><td>2</td><td>3</td><td class="active">+</td></tr>
        <tr><td>+/-</td><td>0</td><td>.</td><td id="result" class="active">=</td></tr>
    </table>
    <div id="CalculatorHistory" style="display:none">
        <table id="CalculatorHistoryTable" class="table table-bordered">
            <thead><tr><th>History</th></tr></thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr><td>@item.CalculatorExpression=@item.CalculatorResult</td></tr>
                }
            </tbody>
        </table>
    </div>
    @section scripts{
        <script>
            $("#Calculator").on('click', 'td', function (event) {
                $('.success').removeClass('success');
                $(this).addClass('success');
                if ($(this).html() == "C") {
                    $("#show").val('');
                } else if ($(this).html() == "delete") {
                    $("#show").val($("#show").val().substring(0, ($("#show").val().length - 1)));
                }else if ($(this).html() != "=") {
                    if ($(this).html() == "+/-") {
                        $("#show").val($("#show").val() + "-");
                    } else{
                        $("#show").val($("#show").val() + $(this).html());
                    }
                }
            });
            $('#result').click(function () {
                var calculatestring = $("#show").val();
                $("#hiddenshow").val(calculatestring);
                $.ajax({
                    url: "@Url.Action("compute")",
                    data: { input: calculatestring},
                    type: "POST",
                    success: function (data) {
                        $("#show").val(data);
                        saveToDatabase($("#hiddenshow").val(), data);
                        $('.success').removeClass('success');
                    }
                })
    
            });
            function saveToDatabase(calculatorExpression, calculatorResult){
                $.ajax({
                    url: "@Url.Action("saveToDatabase")",
                    data: { CalculatorExpression: calculatorExpression, CalculatorResult: calculatorResult },
                    type: "POST",
                    success: function (data) {
                        $("#CalculatorHistory").html(data);
                        CalculatorHistory();
                    }
                });
            }
            $('#ShowCalculatorHistory').click(function () {
                if ($("#CalculatorHistory").css('display') == 'none') {
                    $("#CalculatorHistory").show();
                } else {
                    $("#CalculatorHistory").hide();
                }
            });
            $(function () {
                CalculatorHistory();
            });
            function CalculatorHistory() {
                $("#CalculatorHistoryTable").on('click', 'tr', function (event) {
                    $('.success').removeClass('success');
                    var currenttd = $(this).find("td");
                    $("#show").val(currenttd.html().split("=")[0]);
                });
            }
        </script>
    }

    _CalculatorHistory

    @model IEnumerable<CalculatorDemo.Models.Calculator>
    <table id="CalculatorHistoryTable" class="table table-bordered">
        <thead><tr><th>History</th></tr></thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr><td>@item.CalculatorExpression=@item.CalculatorResult</td></tr>
            }
        </tbody>
    </table>

    Here is the result.

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 4, 2020 6:31 AM
  • User-462092770 posted

    Thank you man, that really will help me :) I will try to mix/adapt my code with yours .... that will save mee a lot of time

    I colud provide you with my code if you want. But what i just want to know is  ----> would for example: your calculator work without a Database. OOr is Database the only Solution.

    Friday, September 4, 2020 7:09 AM