简体   繁体   English

无法从我的AJAX发布请求中获取数据

[英]Cant get a the data from my AJAX post request

I'm currently working on a ASP.net core 2.0 web app. 我目前正在使用ASP.net core 2.0 Web应用程序。 And I want to parse a selected product id to the controller trough AJAX. 我想将选定的产品ID解析到控制器通过AJAX的通道。 In the controller I want to store it trough session or something. 在控制器中,我想通过会话或其他方式存储它。 So far I can get a connection from AJAX to my Controller but my parameter is always null. 到目前为止,我可以获得从AJAX到Controller的连接,但是我的参数始终为null。 The connection between my .js file and the Controller is not the problem. 我的.js文件和Controller之间的连接不是问题。 Here is my code: 这是我的代码:

My HTML 我的HTML

@Model  PCBuild.Models.PCBuildIndexModel
@{
    ViewData["Title"] = "PC-Builder";
}
<asp:HiddenField ID="Selector" runat="server"/>
<div class="container-fluid" style="padding-top: 10px">
    <div class="row">
        <div class="col-sm-6" style="border-right: solid 1px #efefef">
            <div class="container-fluid">
                <form asp-action="SendPcPart" method="post">
                    <div class="row">
                        <div class="col-sm-9">
                            <h3>All parts:</h3>
                            <div class="list-group">
                                @foreach (var part in Model.PcParts)
                                {
                                    <a class="list-group-item pcselector" data-href="@part.EAN">@part._Name</a>
                                }
                            </div>
                        </div>
                        <div class="col-sm-3">
                            <h5>Selected part: </h5>
                            <br />
                            <button class="btn-primary">Add</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <div class="col-sm-6">
            <h3>Selected Items:</h3>
            <ul class="list-group"></ul>
        </div>
    </div>
</div>

This is my .js file containing the AJAX: 这是我的.js文件,其中包含AJAX:

$(document).ready(function() {
$('.pcselector').click(function () {
    var pcPart = {
        EAN: $(this).data('href')
    };
    console.log(pcPart);

    $.ajax({
        type: "POST",
        url: '/PCBuild/SelectPcPart',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: pcPart,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        success: function(result) {
            console.log(result);
        },
        error: function(result) {
            console.log(result);
        }
    });
});

The .pcselector has a data-heref = "1"; .pcselector的data-heref = "1"; So the EAN has a value of 1. 因此EAN的值为1。

My ASP.net Core 2.0 Controller: 我的ASP.net Core 2.0控制器:

[ValidateAntiForgeryToken]
[HttpPost]
public IActionResult SelectPcPart([FromForm] PcPart pcPart)
{
    return new JsonResult("Hello response back" + pcPart);
}

My PcPart class: 我的PcPart类:

public class PcPart
{
    public int EAN { get; set; }
    public string _Name { get; set; }
    public string _Type { get; set; }
    public string Information { get; set; }
    public List<Propertie> Properties { get; set; }
}

I also replaced the [FromForm] with [FromBody] but that has no effect. 我也换成了[FromForm][FromBody]但没有任何效果。 I always get a empty PcPart class. 我总是得到一个空的PcPart类。 I also removed it completely but that doesn't work either. 我也将其完全删除,但这也不起作用。

I also tried this version of my .js file: 我还尝试了此版本的.js文件:

$(document).ready(function() {
$('.pcselector').click(function () {
    var pcPart = EAN: $(this).data('href');
    console.log(pcPart);

    $.ajax({
        type: "POST",
        url: '/PCBuild/SelectPcPart',
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: pcPart,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        success: function(result) {
            console.log(result);
        },
        error: function(result) {
            console.log(result);
        }
    });
});

But that doesn't work either. 但这也不起作用。

A screenshot of the empty class i get Click here 我得到的空课程的屏幕截图单击此处

A screenshot of my console Click here 我的控制台的屏幕截图单击此处

FIXED 固定
My javascript: 我的JavaScript:

var pcPart = {
        "EAN": $(this).attr('data-href')
    };


data: JSON.stringify(pcPart),

My Controller: 我的控制器:

[ValidateAntiForgeryToken]
[HttpPost]
public IActionResult SelectPcPart([FromBody] PcPart pcPart)
{
    return null;
}

The solution from @Camilo Terevinto is enough but if still not working then try using JSON.stringify(). @Camilo Terevinto提供的解决方案就足够了,但是如果仍然无法解决问题,请尝试使用JSON.stringify()。 Try this out 试试看

var dto = {
    pcPart: {
        EAN: $(this).data('href')
    }
};
console.log(dto);

$.ajax({
    type: "POST",
    url: '/PCBuild/SelectPcPart',
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(dto),
    beforeSend: function(xhr) {
        xhr.setRequestHeader("XSRF-TOKEN",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    success: function(result) {
        console.log(result);
    },
    error: function(result) {
        console.log(result);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM