0

I want to calculate addition of two numbers in asp.net mvc.My code is below.

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

    public JsonResult Calculate(int a,int b)
    {
        return Json(a + b);
    }

Index.cshtml code is below:

 <table>
    <tr>
        <td><input type="text" id="s1"/></td>
        <td>+</td>
        <td><input type="text" id="s2"/>=</td>
        <td><div id="result"></div></td>
    </tr>
    <tr><td><input type="submit" value="Calculate" id="btnCalc"/></td></tr>
</table>
<script type="text/javascript">
    $(document).ready(function () {
        $('#btnCalc').click(function () {
            var a = $('#s1').val(),b=$('#s2').val();
            $.post("/Home/Calculate", { a: a,b:b }, function (data) {
                $('#result').text(data.Text);
            }, "json");
        });
    });
</script>

But when I click to calculate button nothing happened.Where I am wrong.(Sorry my english is bad :( )

2
  • What do you mean "nothing happens"? Is there an error message in the console? Commented Nov 14, 2013 at 18:13
  • don't show anything in result div Commented Nov 14, 2013 at 18:24

2 Answers 2

1

In your javascript, you need to do this:

var a = $('#s1').val();
var b = $('#s2').val();

// {a: a, b: b} might work, but I can't test it right now
$.post('/home/calculate', 'a=' + a + '&b=' + b, function(data) {
    $('#result').text(data.Text);
});

In your controller:

[HttpPost] //This isn't required, but it will prevent GET requests if that's what you want to do
public JsonResult(int a, int b)
{
    int result = a + b;
    return Json(new {Text = result});
}

The main problem is that in your javascript, you were referencing a Text property of data, but you weren't returning that from your controller

Sign up to request clarification or add additional context in comments.

Comments

0

I found my mistake. Might be helpful to someone.

<table>
<tr>
    <td><input type="text" id="s1"/>+</td>
   <td><input type="text" id="s2"/>=</td>
    <td><div id="result"></div></td>
</tr>
<tr>
    <td><input type="submit" id="btn"/></td></tr>
<script type="text/javascript">
    $(document).ready(function () {
        $("#btn").click(function() {
            var a = $('#s1').val();
            var b = $("#s2").val();
            $.post("/Home/Calc", { a: a,b:b}, function (data) {
                $('#result').text(data.Text);
            }, "json");
        });});
 [HttpPost]
        public JsonResult Calc(int a,int b)
        {
            int result = a + b;
            return Json(new {Text=result});
        }

        public class Result
        {
            public string Text { get; set; }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.