Asp.net MVC using json



我想计算代码中两个数字的相加 asp.net mvc.My 如下。

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

Index.cshtml代码如下:

 <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>

但是当我单击以计算按钮时,没有任何反应。我错了。(对不起,我的英语不好:()

在你的 JavaScript 中,你需要这样做:

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);
});

在控制器中:

[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});
}

主要问题是在你的javascript中,你引用了一个Text属性data,但你没有从你的控制器返回它。

我发现了我的错误。可能对某人有帮助。

<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; }
        }

最新更新