簡體   English   中英

通過AJAX將數據傳遞到MVC中的控制器

[英]Pass Data by AJAX to Controller in MVC

我正在嘗試將數據傳遞給控制器​​以進行進一步處理,但控制器中為空,但是無論如何,js(ajax)的調試都會顯示該數字。 可能是什么問題?

阿賈克斯:

 $('.toggler_btn').on('click', function (event)
            {
                var id = $(this).attr('data-id');
                    if ($(this).text() === '+') {
                        $.ajax({
                            url: "/List/GetSubItems",
                            type: "POST",
                            contentType: "html",
                            dataType: "text",
                            data: '{"id":"' + id + '"}', // here it show the data, like 5 or some other number
                            success: function (data)
                            {
                                $('.element_wrapper [data-id="' + id + '"]').html(data);
                            }
                            })
                        $(this).html('-');
                    }
                    else $(this).html('+');
            });

控制器:

  [HttpPost]
    public ActionResult GetSubItems(string id) // here I get null
    {
        int pID = 0;
        int.TryParse(id, out pID);
        List<H_Table> list = new List<H_Table>();

        foreach (var item in db_connection.H_Table.Where(i => i.PARENT_ID == pID))
        {
            list.Add(item);
        }
        return PartialView(list);
    }
$('.toggler_btn').on('click', function (event) {
    var id = $(this).attr('data-id');
    if ($(this).text() === '+') {
        $.ajax({
            url: '/List/GetSubItems',
            type: 'POST',
            dataType: 'json',
            data: '{"id":"' + id + '"}',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $('.element_wrapper [data-id="' + id + '"]').html(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("responseText=" + XMLHttpRequest.responseText + "\n textStatus=" + textStatus + "\n errorThrown=" + errorThrown);
            }
        });
        $(this).html('-');
    }
    else $(this).html('+');
});

使用這個只需復制和粘貼

將您的內容類型更改為“文本”,並更改數據。

您的AJAX請求已設置了contentType: "html"但實際上您正在發送JSON( data: '{"id":"' + id + '"}' )。 並且您的控制器正在接收string

因此,要么更改您的AJAX調用以發送原始字符串:

contentType: "text",
data: { id: id }

...或更新您的控制器以接收JSON。 后者可以通過創建如下代碼來實現:

public ActionResult GetSubItems(ViewModel model)

public class ViewModel {
    public string Id { get; set; }
}

編輯 :另外,作為參考,您可能希望查看contentTypedataType之間區別

將數據類型更改為“ application / json”,並將數據更改為此:

   data :{
          id : id
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM