javascript Ajax 将空值传递给控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32255671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:02:10  来源:igfitidea点击:

Ajax passing null value to controller

javascriptajaxasp.net-mvcmodel-view-controllerasp.net-ajax

提问by failsatheals

I have a dropdown that has a list of ID's in it. The customer will select one and it will reflect a price total on the page. Im creating an ajax call that will update the total when a different ID is pulled from the Dropdown.

我有一个下拉列表,其中包含一个 ID 列表。客户将选择一个,它将在页面上反映总价格。我正在创建一个 ajax 调用,当从下拉列表中提取不同的 ID 时,它将更新总数。

$("#BrandId").on('focus', function () {
    // Store the current value on focus and on change
    previous = this.value;
}).change(function () {
    alert("Previous: " +previous);
    sel = this.value;
    alert("Selected: " +sel);
    $.ajax({
        cache: false,
        type: "get",
        contentType: "application/json; charset=utf-8",
        url: '@Url.Action("GetBrandCost", "Shocks")',
        data: JSON.stringify({ idp: previous, id: sel }),
        dataType: "json",
        aysnc: false,
        success: function (data1) {
            alert(data1);
                //ShockTotal = $("#ShockTotal").html();
                //ShockTotal = ShockTotal / 1;
                ////ShockTotal = ShockTotal - data1;
                //$("#ShockTotal").html(data1);

        }
    });
});

The alerts are working perfectly but the ajax isnt passing those ID's into the controller, the controller is just receiving nulls.

警报工作正常,但 ajax 没有将这些 ID 传递给控制器​​,控制器只是接收空值。

 public decimal GetBrandCost(string idp, string id)
    {
        decimal costp = 0;
        decimal cost = 0;
        if (id == "" || id == null || idp == "" || idp == null)
        {
            return 0;
        }
        ShockBrand brandp = db.ShockBrands.Find(idp);
        costp = brandp.Cost;
        ShockBrand brand = db.ShockBrands.Find(id);
        cost = brand.Cost;
        cost = cost - costp;
        return cost;
    }

Since they are null I am hitting my if statement and just returning zero inside the success. Most of the things I read were to add the content type but that didnt seem to help in my case, Im sure it is something little.

由于它们为空,因此我正在使用 if 语句并在成功中返回零。我阅读的大部分内容都是添加内容类型,但这对我来说似乎没有帮助,我确定这是小事。

回答by Medet Tleukabiluly

From browser console, this

从浏览器控制台,这个

$.ajax({
        cache: false,
        type: "get",
        contentType: "application/json; charset=utf-8",
        url: 'http://google.com',
        data: JSON.stringify({ idp: 1, id: 2 }),
        dataType: "json",
        aysnc: false,
        success: function (data1) {
           console.log(data1)

        }
    });

returns request to http://google.com/?{%22idp%22:1,%22id%22:2}&_=1440696352799, which is incorrect

将请求返回给http://google.com/?{%22idp%22:1,%22id%22:2}&_=1440696352799,这是不正确的

and without stringify

并且没有字符串化

$.ajax({
        cache: false,
        type: "get",
        contentType: "application/json; charset=utf-8",
        url: 'http://google.com',
        data: { idp: 1, id: 2 },
        dataType: "json",
        aysnc: false,
        success: function (data1) {
           console.log(data1)

        }
    });

returns http://google.com/?idp=1&id=2&_=1440696381239(see Network tab)

退货http://google.com/?idp=1&id=2&_=1440696381239(参见网络标签)

So don't use JSON.stringify

所以不要使用 JSON.stringify

Why it's gonna work - your asp.net controller action receives simple typed parameters (string, numbers, etc) and jquery is fairly enought smart to determine what are going to send, if it was object inside object it will send it as POST data for POST, and string represenation of object for GET (you have GET request, but for purpose of knowledge, just stick with 2 types of data that can be send, params& data) So when jquery configures url, asp.net understands conventions, and matches request to approciated action

为什么它会起作用 - 你的 asp.net 控制器动作接收简单的类型参数(字符串、数字等),jquery 相当聪明地确定要发送的内容,如果它是对象内的对象,它将作为 POST 数据发送给POST 和 GET 对象的字符串表示(您有 GET 请求,但出于知识目的,只需坚持使用 2 种可以发送的数据类型,paramsdata)因此,当 jquery 配置 url 时,asp.net 理解约定,并且匹配请求到适当的动作

But Don't believe me, check it yourself

但别相信我,你自己检查一下

chrome dev console is your friend

chrome dev 控制台是你的朋友

回答by Ravi

you can just put like var dataReq={ idp: previous, id: sel }; data: dataReq

你可以像 var dataReq={ idp: previous, id: sel }; 数据:数据请求

and no need to use dataType and contentType

并且不需要使用 dataType 和 contentType