传递参数在阿贾克斯得到空值 [英] passing parameter in ajax gets null value

查看:198
本文介绍了传递参数在阿贾克斯得到空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AJAX,但我通过与的数据属性总是时动作控制器接收它空参数调用一个动作控制器... $ B ?$ b什么能在这里发生在



JQuery的功能:

 后序功能()
{
VAR ID = $(aslink)的数据(客户id);
VAR URL = $(#btnAddOrderPost)的数据(url_add_order);
$阿贾克斯({
型:后,
网址:网址,
数据:JSON.stringify({orderVM:$(#frmCreatePV)连载( )}),
数据类型:JSON,
的contentType:应用/ JSON,
成功:函数(){
警报(它被插入);
}
})
}

动作控制器:

  [HttpPost] 
// [ValidateAntiForgeryToken]
公众的ActionResult CreatePV(orderVM orderVM)
$ { b $ b如果(ModelState.IsValid)
{
名单,LT;字符串>顶部=新名单<串GT;();
十进制tempPrice = 0M;
的for(int i = 0; I< orderVM.Toppings.Count;我++)
{
如果(orderVM.Toppings [I] .IsSelected == true)而
{
top.Add(orderVM.Toppings [I] .SpecificTopping);
tempPrice + = orderVM.Toppings [I]。价格;
}
}
订购订购=新订单
{
浇头=顶部,
TotalPrice = tempPrice
};
db.Orders.Add(订单);
db.SaveChanges();
返回RedirectToAction(「指数」);
}
返回查看(orderVM);
}

这是OrderVM视图模型我使用这种类型的参数:

 公共类OrderVM 
{
公共虚拟目录< ToppingVM>浇头{搞定;组; }
公共小数TotalPrice {搞定;组; }
}



这是包含的局部视图里面的表单:

  @using(Html.BeginForm(NULL,NULL,FormMethod.Post,htmlAttributes:新的{@ ID =frmCreatePV})) 
{
@ Html.AntiForgeryToken()
< DIV CLASS =形横>
@ Html.ValidationSummary(真,新{@class =TEXT-危险})
< DIV CLASS =表单组>
@ {
的for(int i = 0; I< Model.Toppings.Count;我++)
{
< DIV CLASS =COL-XS-4> ;
@ Html.HiddenFor(型号=> model.Toppings [I] .SpecificTopping)
@ Html.CheckBoxFor(型号=> model.Toppings [I] .IsSelected,htmlAttributes:新{data_price = model.Toppings [I]。价格,@id =chbkPrice})
@ Html.HiddenFor(型号=> model.Toppings [I]。价格)
@ Html.LabelFor(型号= > model.Toppings [I] .IsSelected,Model.Toppings [I] .SpecificTopping)
< p>价格:@ Model.Toppings [I]。价格< / p>
< / DIV>
}
}
< / DIV>
< DIV CLASS =表单组>
< DIV CLASS =COL-MD-10>
<输入类型=按钮值=添加命令ID =btnAddOrderPost级=BTN BTN-主要
数据url_add_order =@ Url.Action(CreatePV,订单)/>
< / DIV>
< / DIV>
< / DIV>
}



更新



最后,这是动作控制器如何住:

  [HttpPost] 
[ValidateAntiForgeryToken]
公共JsonResult CreatePV(orderVM orderVM)
{
INT ID = Convert.ToInt32(TempData的[许可证]);
如果(ModelState.IsValid)
{
名单,LT;字符串>顶部=新名单<串GT;();
十进制tempPrice = 0M;
的for(int i = 0; I< orderVM.Toppings.Count;我++)
{
如果(orderVM.Toppings [I] .IsSelected == true)而
{
top.Add(orderVM.Toppings [I] .SpecificTopping);
tempPrice + = orderVM.Toppings [I]。价格;
}
}
订购订购=新订单
{
客户= db.Customers.Where(C => c.LicenseNumber == ID)。首先( ),
LicenseNumber = ID,
浇头=顶部,
TotalPrice = tempPrice
};
db.Orders.Add(订单);
db.SaveChanges();
返回JSON(新{成功=真,JsonRequestBehavior.AllowGet});
}
返回JSON(新{成功=假,JsonRequestBehavior.AllowGet});
}

和JQuery的功能,请注意,我利用serializeArray的()添加对数据元素,这不是绑定到HTML表单:

 功能后序()
{
变种orderVM = {};
ID = $(。aslink)的数据(客户id);
警报($(#btnGetOrderAdd)的数据(客户id));
VAR URL = $(#btnAddOrderPost)的数据(url_add_order);
变种datavar = $(#frmCreatePV)serializeArray();
datavar.push({名:LicenseNumber,值:ID})
$阿贾克斯({
型:后,
网址:网址,
数据:datavar,
数据类型:JSON,
成功:函数(){
警报(它被插入);
}
})
}


解决方案

删除的contentType 会为你工作。



的contentType 是你的数据类型发送,这样,应用程序/ JSON的;字符集= UTF-8是一种常见的,因为是应用程序/ x-WWW的形式,进行了urlencoded; 。字符集= UTF-8,这是默认



在使用的contentType:应用/ JSON 你会不能依靠被填充$ _ POST。 $ _ POST中只填入形式编码的内容类型。



在这种情况下,您可以访问PHP的原始数据。

  $输入=的file_get_contents('PHP://输入'); 
$ =对象json_encode($输入);



希望这可以帮助你:)


I'm calling an action controller using ajax but the parameter I'm passing with the data attribute is always null when the action controller receives it... What could be happening in here?

JQuery function:

function PostOrder()
{      
    var id = $(".aslink").data("customerid");
    var url = $("#btnAddOrderPost").data("url_add_order");       
    $.ajax({
        type:"post",
        url: url,
        data: JSON.stringify( { orderVM: $("#frmCreatePV").serialize()}),
        datatype: "json",
        contentType: "application/json",
        success: function () {
            alert("it was inserted");
        }
    })
}

Action controller:

[HttpPost]
   // [ValidateAntiForgeryToken]
    public ActionResult CreatePV(OrderVM orderVM)
    {
        if (ModelState.IsValid)
        {
            List<string> top = new List<string>();
            decimal tempPrice = 0M;
            for (int i = 0; i < orderVM.Toppings.Count; i++)
            {
                if (orderVM.Toppings[i].IsSelected == true)
                {
                    top.Add(orderVM.Toppings[i].SpecificTopping);
                    tempPrice += orderVM.Toppings[i].Price;
                }
            }
            Order order = new Order
            {                 
                Toppings = top,
                TotalPrice = tempPrice
            };
            db.Orders.Add(order);
            db.SaveChanges();
            return RedirectToAction("Index");
        }            
        return View(orderVM);
    }

This is the OrderVM ViewModel I'm using a parameter of this type:

public class OrderVM
{           
    public virtual List<ToppingVM> Toppings { get; set; }
    public decimal TotalPrice { get; set; }
}

And this is the form which is contained inside a Partial View:

@using (Html.BeginForm(null,null,FormMethod.Post, htmlAttributes: new { @id="frmCreatePV"}))
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @{
                for (int i = 0; i < Model.Toppings.Count; i++)
                {
                    <div class="col-xs-4">
                        @Html.HiddenFor(model => model.Toppings[i].SpecificTopping)                       
                        @Html.CheckBoxFor(model => model.Toppings[i].IsSelected, htmlAttributes: new { data_price = Model.Toppings[i].Price, @id = "chbkPrice" })                      
                        @Html.HiddenFor(model => model.Toppings[i].Price)
                         @Html.LabelFor(model => model.Toppings[i].IsSelected , Model.Toppings[i].SpecificTopping)                        
                        <p>Price: @Model.Toppings[i].Price</p>
                    </div>
                }
            }
        </div>
        <div class="form-group">
            <div class="col-md-10">
                <input type="button" value="Add order" id="btnAddOrderPost" class="btn btn-primary"
                       data-url_add_order="@Url.Action("CreatePV", "Orders")" />
            </div>
        </div>
    </div>
                }

UPDATE

Finally this is how the Action Controller stayed:

  [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult CreatePV(OrderVM orderVM)
    {
        int id = Convert.ToInt32(TempData["License"]);
        if (ModelState.IsValid)
        {
            List<string> top = new List<string>();
            decimal tempPrice = 0M;
            for (int i = 0; i < orderVM.Toppings.Count; i++)
            {
                if (orderVM.Toppings[i].IsSelected == true)
                {
                    top.Add(orderVM.Toppings[i].SpecificTopping);
                    tempPrice += orderVM.Toppings[i].Price;
                }
            }
            Order order = new Order
            {
                Customer = db.Customers.Where(c => c.LicenseNumber == id).First(),
                LicenseNumber = id,
                Toppings = top,
                TotalPrice = tempPrice
            };
            db.Orders.Add(order);
            db.SaveChanges();
            return Json(new { success= true, JsonRequestBehavior.AllowGet});
        }           
        return Json(new { success = false, JsonRequestBehavior.AllowGet});
    }

And the JQuery function, note that I made use of serializeArray() to add an element to the data that was not bound to the html form :

function PostOrder()
{
    var orderVM = {};   
    id = $(".aslink").data("customerid");
    alert($("#btnGetOrderAdd").data("customerid"));
    var url = $("#btnAddOrderPost").data("url_add_order");
    var datavar = $("#frmCreatePV").serializeArray();
    datavar.push({name: "LicenseNumber" ,value : id})  
    $.ajax({
        type:"post",
        url: url,       
        data: datavar,
        datatype: "json",      
        success: function () {
            alert("it was inserted");
        }
    })
}

解决方案

Remove contentType will work for you.

contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.

When using contentType: 'application/json' you will not be able to rely on $_POST being populated. $_POST is only populated for form-encoded content types.

In that case, you can access the PHP raw data.

$input = file_get_contents('php://input');
$object = json_encode($input);

Hope this helps you :)

这篇关于传递参数在阿贾克斯得到空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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