如何在我的控制器Actionresult方法中获取Ajax数据 [英] How Do I Get Ajax Data In My Controller Actionresult Method

查看:57
本文介绍了如何在我的控制器Actionresult方法中获取Ajax数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Ajax接收字符串对象/字符串,但在我的Controller方法中,我在我的数据参数中得到Null。那么我怎么得到trip_text消息是我的控制器方法。



我的旅行控制器

----------- -------

I want to receive string object/string from Ajax but on my Controller method, i am getting Null in my data parameter. So how do i get trip_text message is my controller method.

My Trip Controller
------------------

[HttpPost]
public ActionResult Posts(string data)
{
    Response.Write(data);
    return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
}



我的JQuery代码是这样的

---------------- -------


My JQuery code is like this
-----------------------

var trip_text = document.getElementById("txtPost").value;
       $.ajax({

           url: '/Trip/Posts',
           dataType: "json",
           type: "POST",
           contentType: 'application/json; charset=utf-8',
           cache: false,
           data: JSON.stringify(trip_text),
           success: function (data) {
               alert(data.message);
           },
           error: function (xhr) {
               alert("Error");
           }
       });

推荐答案

.ajax({

url:' / Trip / Posts'
dataType: json
type: POST
contentType:' application / json; charset = utf-8'
cache: false
data: JSON .stringify(trip_text),
成功:功能(数据){
alert(data.message);
},
错误: function (xhr){
alert( 错误);
}
} );
.ajax({ url: '/Trip/Posts', dataType: "json", type: "POST", contentType: 'application/json; charset=utf-8', cache: false, data: JSON.stringify(trip_text), success: function (data) { alert(data.message); }, error: function (xhr) { alert("Error"); } });


您不需要 HttpPost ,因为您没有发布内容服务器,仅基于您获得响应的参数。 HttpGet 会为你做的。

You don't need HttpPost, as you're not posting something to the server, only based upon parameter you're getting response. HttpGet would do for you.
public ActionResult Posts(string data)
{
    if(data == "SomePost")
    {
        return Json(new { success = true, message = "Order updated successfully" }, JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json(new { success = false, message = "Oops! Something went wrong" }, JsonRequestBehavior.AllowGet);
    }
}



现在你是AJAX电话,


Now you're AJAX call,


.ajax({
url:' ../ Trip / Posts ' // 或者我建议您使用@ Url.Action(帖子,旅行)
dataType: json
type : GET // < span class =code-comment> get request
contentType:' application / json; charset = utf-8'
cache: false
data:
.ajax({ url: '../Trip/Posts', // or I'd suggest you to use @Url.Action("Posts", "Trip") dataType: "json", type: "GET", // get request contentType: 'application/json; charset=utf-8', cache: false, data:


这篇关于如何在我的控制器Actionresult方法中获取Ajax数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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