首页 文章

使用jquery asp.net mvc调用ajax

提问于
浏览
0

我有一个类“btn”的按钮,其中包含id“ajaxtest” . 当我点击按钮时,我想在我的span标签中输入文本“test” . 这要在ASP.NET MVC中完成 .

在视图中我有以下ajax调用:

<span id="ajaxtest"></span>
<input type="submit" class="btn" name="neverMind" value="Test BTN"/>

    <script>
    $(document).ready(function () {
        $(".btn").click(function () {
            $.ajax({
                method: "get",
                cache: false,
                url: "/MyController/MyAction",
                dataType: 'string',
                success: function (resp) {                       
                    $("#ajaxtest").html(resp);
                }
            });
        });
    });
    </script>

在MyController中,我有以下代码:

public string MyAction()
    {
        return "test";
    }

我知道Ajax是如何工作的,我知道MVC是如何工作的 . 我知道错误可能是因为我们在控制器中期待这样的事情:

public ActionResult MyAction()
    {
        if (Request.IsAjaxRequest())
        {
              //do something here
        }
        //do something else here
    }

但实际上那是我的问题 . 我不想通过这个电话打电话给部分观看 . 我只想在我的范围内返回一些字符串,我想知道是否可以在不使用其他部分视图的情况下完成此操作 .

我想使用只返回字符串的简单函数 .

1 回答

  • 3

    将dataType:'string'更改为dataType:'text'

    <script>
                $(document).ready(function () {
                    $(".btn").click(function () {
                        $.ajax({
                            method: "get",
                            cache: false,
                            url: "/login/MyAction",
                            dataType: 'text',
                            success: function (resp) {
                                $("#ajaxtest").html(resp);
                            }
                        });
                    });
                });
            </script>
    

    我检查它是我的本地它将对我有用

相关问题