Home > other >  Calculator Using Ajax and Asp.Net MVC
Calculator Using Ajax and Asp.Net MVC

Time:11-15

I am creating a simple calculator using asp.net mvc and ajax, here is the code.

 public ActionResult Index()
        {
            return View(new Calculator_Model());
        }

        [HttpPost]
        public ActionResult Index(Calculator_Model cal,string calculate)
        {
            if (calculate == "add")
            {
                cal.Total = cal.Number1   cal.Number2;
            }
            else if (calculate == "sub")
            {
                cal.Total = cal.Number1 - cal.Number2;
            }
            else if (calculate == "multi")
            {
                cal.Total = cal.Number1 * cal.Number2;
            }
            else if (calculate == "divis")
            {
                cal.Total = cal.Number1 / cal.Number2;
            }

            return Json(cal);

        }

The model page is

    public class Calculator_Model
    {
        public int Number1 { get;set; }
        public int Number2 { get;set; }
        public int Total { get;set; }

    }

and the view page is


@model Calculator.Models.Calculator_Model

@{
    ViewBag.Title = "Index";
}

@using (Ajax.BeginForm("index", "Calculator",
    new AjaxOptions()
    {
        HttpMethod = "POST",
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "Total",
    }
    ))
{
        <input type="number"  name="Number1" value="@Model.Number1" />

        <input type="number"  name="Number2" value="@Model.Number2" />

        <div>
        <input type="number" name="Total" value="@Model.Total" disabled />
        <div id="Total">
        </div>
        </div>

        <button type="submit" name="calculate" value="add"> </button>
        <button type="submit" name="calculate" value="sub">-</button>
        <button type="submit" name="calculate" value="multi">*</button>
        <button type="submit" name="calculate" value="divis">/</button>
}


The logic works fine, but i want that the result of the calculator would be displayed in the disabled input tag.

Anyone here to help me.

I am expecting that the result would come in the disable input box.

CodePudding user response:

I am expecting that the result would come in the disable input box.

Well, if you are expecting to display the result in Total inputbox in disable mood you can simply do do that in following way:

Controller:

public class CalculatorController : Controller
    {
        public ActionResult Index()
        {
            return View(new Calculator_Model());
        }

        [HttpPost]
        public ActionResult Index(Calculator_Model cal, string calculate)
        {
            if (calculate == "add")
            {
                cal.Total = cal.Number1   cal.Number2;
            }
            else if (calculate == "sub")
            {
                cal.Total = cal.Number1 - cal.Number2;
            }
            else if (calculate == "multi")
            {
                cal.Total = cal.Number1 * cal.Number2;
            }
            else if (calculate == "divis")
            {
                cal.Total = cal.Number1 / cal.Number2;
            }

            return View("Index",cal);

        }

    }

Note: Instead of returning Json(cal); you can return to index action with your latest model state as return View("Index",cal);

View:

@model DotNet6MVCWebApp.Controllers.Calculator_Model

@{
    ViewBag.Title = "Index";
}
<form asp-controller="Calculator" method="post" asp-action="Index">
    <div >
        <div >
            <label asp-for="Number1" ></label>
            <input asp-for="Number1"  placeholder="Enter first number" />
            <span asp-validation-for="Number1" ></span>
        </div>
        <div >
            <label asp-for="Number2" ></label>
            <input asp-for="Number2"  placeholder="Enter second number" />
            <span asp-validation-for="Number2"  ></span>
        </div>

        <div >
            <label asp-for="Total" ></label>
            <input asp-for="Total"  value="@Model.Total" disabled />
            <span asp-validation-for="Number2" ></span>
        </div>
        <div  style="margin-top:5px">
            <button type="submit" name="calculate"  value="add"><strong> </strong></button>
            <button type="submit" name="calculate"  value="sub"><strong>-</strong></button>
            <button type="submit" name="calculate"  value="multi"><strong>*</strong></button>
            <button type="submit" name="calculate"  value="divis"><strong>/</strong></button>
        </div>
    </div>
</form>

Pure Ajax Javascript Example:

<div>
    <input id="Number1"  placeholder="Enter first number" />
    <input id="Number2"  placeholder="Enter second number" />
    <input id="Total"  value="" disabled />
    <button type="submit" name="calculate"  value="add"><strong> </strong></button>
    <button type="submit" name="calculate"  value="sub"><strong>-</strong></button>
    <button type="submit" name="calculate"  value="multi"><strong>*</strong></button>
    <button type="submit" name="calculate"  value="divis"><strong>/</strong></button>
</div>

@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script>
        $(document).ready(function () {

            $("button").click(function () {
                var operation = $(this).val();
                var data = {
                    Number1: $("#Number1").val(),
                    Number2: $("#Number2").val(),
                }
                console.log(data);
                $.ajax({
                    type: "POST",
                    url: 'http://localhost:5094/Calculator/Post?calculate='   operation,
                    datatype: "json",
                    data: data,
                    success: function (res) {
                        console.log(res);
                        $("#Number1").val(res.number1);
                        $("#Number2").val(res.number2);
                        $("#Total").val(res.total);
                    },
                    error: function () {
                        alert("It failed");
                    }
                });
                return false;
            });
        });
    </script>
}

Note: Well, based on your comment here is the clean ajax example. If you use this pattern than return the controller value as returnJson(cal);`

Output:

enter image description here

This is much cleaner way what you are trying to implement.

  • Related