在asp.net mvc中对控制器进行简单的Ajax调用

问题描述 投票:98回答:9

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

控制器:

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”。警报未触发。

UPDATE

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

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

        [HttpPost]
        public ActionResult FirstAjax(string a)
        {
            return Json("chamara", JsonRequestBehavior.AllowGet);
        }
    }
c# jquery asp.net asp.net-mvc asp.net-mvc-2
9个回答
22
投票

完成更新后,

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

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

您不能直接呈现JSON的普通数据而不是HTML。


49
投票

删除数据属性,因为您不是POSTING任何东西到服务器(您的控制器不期望任何参数)。

在你的AJAX方法中,你可以使用Razor并使用@Url.Action而不是静态字符串:

$.ajax({
    url: '@Url.Action("FirstAjax", "AjaxTest")',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: successFunc,
    error: errorFunc
});

从您的更新:

$.ajax({
    type: "POST",
    url: '@Url.Action("FirstAjax", "AjaxTest")',
    contentType: "application/json; charset=utf-8",
    data: { a: "testing" },
    dataType: "json",
    success: function() { alert('Success'); },
    error: errorFunc
});

12
投票

使用Razor通过调用您的操作动态更改您的URL:

$.ajax({
    type: "POST",
    url: '@Url.Action("ActionName", "ControllerName")',
    contentType: "application/json; charset=utf-8",
    data: { data: "yourdata" },
    dataType: "json",
    success: function(recData) { alert('Success'); },
    error: function() { alert('A error'); }
});

4
投票

这是你的更新问题。

由于您不能使用具有相同名称和签名的两个方法,因此必须使用ActionName属性:

更新:

[HttpGet]
public ActionResult FirstAjax()
{
    Some Code--Some Code---Some Code
    return View();
}

[HttpPost]
[ActionName("FirstAjax")]
public ActionResult FirstAjaxPost()
{
    Some Code--Some Code---Some Code
    return View();
}

请参阅this链接,以获取有关方法如何成为动作的进一步参考。虽然很好的参考。


4
投票

首先,不需要在一个页面中有两个不同版本的jquery库,“1.9.1”或“2.0.0”足以使ajax调用工作。

这是您的控制器代码:

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

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

这是您的视图应该是这样的:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function () {
    var a = "Test";
    $.ajax({
        url: "../../Home/FirstAjax",
        type: "GET",
        data: { a : a },
        success: function (response) {
            alert(response);
        },
        error: function (response) {
            alert(response);
        }
    });
});
</script>

3
投票

如果你只需要在你的Ajax Call中点击C#方法,你需要传递两个问题类型和url如果你的请求是get,那么你只需要指定url。请按照下面的代码工作正常。

C#代码:

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

如果获取请求,则为Javascript代码

    $.ajax({
        url: 'home/FirstAjax',
        success: function(responce){ alert(responce.data)},
        error: function(responce){ alert(responce.data)}
    });

如果发布请求的Java脚本代码以及[HttpGet]到[HttpPost]

        $.ajax({
            url: 'home/FirstAjax',
            type:'POST',
            success: function(responce){ alert(responce)},
            error: function(responce){ alert(responce)}
        });

注意:如果您在同一个控制器中使用FirstAjax,那么您的View Controller就不需要在url中使用Controller名称。像url: 'FirstAjax',


1
投票

视图;

 $.ajax({
        type: 'GET',
        cache: false,
        url: '/Login/Method',
        dataType: 'json',
        data: {  },
        error: function () {
        },
        success: function (result) {
            alert("success")
        }
    });

控制器方法;

 public JsonResult Method()
 {
   return Json(new JsonResult()
      {
         Data = "Result"
      }, JsonRequestBehavior.AllowGet);
 }

0
投票

而不是使用url: serviceURL,

url: '<%= serviceURL%>',

你是否将2个参数传递给successFunc?

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

0
投票

在global.asax中添加“JsonValueProviderFactory”:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
© www.soinside.com 2019 - 2024. All rights reserved.