在 asp.net mvc 中对控制器进行简单的 Ajax 调用 [英] Making a Simple Ajax call to controller in asp.net mvc

查看:89
本文介绍了在 asp.net mvc 中对控制器进行简单的 Ajax 调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开始使用 ASP.NET MVC Ajax 调用.

I'm trying to get started with ASP.NET MVC Ajax calls.

控制器:

public class AjaxTestController : Controller
{
    //
    // GET: /AjaxTest/
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult FirstAjax()
    {
        return Json("chamara", JsonRequestBehavior.AllowGet);
    }   
}

查看:

<head runat="server">
    <title>FirstAjax</title>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var serviceURL = '/AjaxTest/FirstAjax';

            $.ajax({
                type: "POST",
                url: serviceURL,
                data: param = "",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data, status) {     
                alert(data);
            }

            function errorFunc() {
                alert('error');
            }
        });
    </script>
</head>

我只需要使用返回数据的控制器方法打印警报.上面的代码只是在我的视图中打印chamara".警报未触发.

I just need to print an alert with the controller method returning data. Above code just print "chamara" on my view. An alert is not firing.

更新

我如下修改了我的控制器,它开始工作了.我不清楚为什么它现在有效.有的请解释一下.参数a"不相关我添加了它,因为我无法添加具有相同方法名称和参数的两个方法.我认为这可能不是解决方案,但它的工作原理

I modified my controller as below and it start working. I don't have an clear idea why it's working now. Some one please explain. The parameter "a" does not related i added it because i can not add two methods with same method name and parameters.I think this might not be the solution but its working

public class AjaxTestController : Controller
    {
        //
        // GET: /AjaxTest/
        [HttpGet]
        public ActionResult FirstAjax()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FirstAjax(string a)
        {
            return Json("chamara", JsonRequestBehavior.AllowGet);
        }
    }

推荐答案

更新完成后,

  1. 它第一次使用默认的 HttpGet 请求调用 FirstAjax 操作并呈现空白的 Html 视图.(之前你没有它)
  2. 稍后加载该视图的 DOM 元素后,您的 Ajax 调用将被触发并显示警报.

之前,您只将 JSON 返回到浏览器而不呈现任何 HTML.现在它呈现了一个 HTML 视图,它可以在其中获取您的 JSON 数据.

Earlier you were only returning JSON to browser without rendering any HTML. Now it has a HTML view rendered where it can get your JSON Data.

您不能直接将 JSON 呈现为纯数据而非 HTML.

You can't directly render JSON its plain data not HTML.

这篇关于在 asp.net mvc 中对控制器进行简单的 Ajax 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆