简体   繁体   中英

Calculator Using Ajax and Asp.Net MVC

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.

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 class="row">
        <div class="form-group">
            <label asp-for="Number1" class="control-label"></label>
            <input asp-for="Number1" class="form-control" placeholder="Enter first number" />
            <span asp-validation-for="Number1" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Number2" class="control-label"></label>
            <input asp-for="Number2" class="form-control" placeholder="Enter second number" />
            <span asp-validation-for="Number2" class="text-danger" ></span>
        </div>

        <div class="form-group">
            <label asp-for="Total" class="control-label"></label>
            <input asp-for="Total" class="form-control" value="@Model.Total" disabled />
            <span asp-validation-for="Number2" class="text-danger"></span>
        </div>
        <div class="form-group" style="margin-top:5px">
            <button type="submit" name="calculate" class="btn btn-primary" value="add"><strong>+</strong></button>
            <button type="submit" name="calculate" class="btn btn-info" value="sub"><strong>-</strong></button>
            <button type="submit" name="calculate" class="btn btn-success" value="multi"><strong>*</strong></button>
            <button type="submit" name="calculate" class="btn btn-warning" value="divis"><strong>/</strong></button>
        </div>
    </div>
</form>

Pure Ajax Javascript Example:

<div>
    <input id="Number1" class="form-control" placeholder="Enter first number" />
    <input id="Number2" class="form-control" placeholder="Enter second number" />
    <input id="Total" class="form-control" value="" disabled />
    <button type="submit" name="calculate" class="btn btn-primary" value="add"><strong>+</strong></button>
    <button type="submit" name="calculate" class="btn btn-info" value="sub"><strong>-</strong></button>
    <button type="submit" name="calculate" class="btn btn-success" value="multi"><strong>*</strong></button>
    <button type="submit" name="calculate" class="btn btn-warning" 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 return Json(cal);`

Output:

在此处输入图像描述

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

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