首页 > 解决方案 > 如何传递 MVC 模型属性列表使用 Javascript Ajax 从我的视图到控制器?

问题描述

这是我的问题:我需要将 List<Export_Admin> 的“export”传递给控制器​​“ExportToExcel”。我尝试了不同的场景,要么收到错误,要么将“null”传递给控制器​​。我不确定语法应该是什么。

在我的视图中,我传递了一个模型:SearchResultsView

@model ResearchDataInventoryWeb.Models.SearchResultsView

我的模型:

public class SearchResultsView
    {
        public SearchResultsView()
        {
            this.datasets = new List<Dataset_Results>();
            this.export = new List<Export_Admin>();
        }
        public List<Dataset_Results> datasets { get; set; }
        public List<Export_Admin> export { get; set; }
    }

我需要将 Model.export 发送回名为 ExportToExcel 的后端控制器

public class Export_Admin
    {
        public string Institution { get; set; }
        public int? Contract_Id { get; set; }
        public string Reference_No { get; set; }
        public string Contract_No { get; set; }
        public string Category { get; set; }
        public string Provider { get; set; }
        public int Dataset_Id { get; set; }
        public string Dataset { get; set; }
        public string Alias { get; set; }
        public string Description { get; set; }
        public string Location { get; set; }
        public string Acq_Start_Date { get; set; }
        public string Expiry_Date { get; set; }
        public string Renewal_Date { get; set; }
        public string Principal_Investigator { get; set; }
        public string url_Dataset { get; set; }
        public string url_Dataset_View { get; set; }
        public string url_Contract { get; set; }
        public string Status { get; set; }
        public string Data_Content { get; set; }
        public string Ext_Collab { get; set; }
        public string Privacy { get; set; }
    }

所以这是我的控制器动作

public ActionResult ExportToExcel(List<Export_Admin> data)
        {
            // Do Something
        }

这是我的阿贾克斯:

  $("#export_id").click(function () {
        var allItem = '@Html.Raw(Json.Encode(Model.export))'
         let myurl = '@Url.Action("ExportToExcel", "Search")';

        $.ajax({
            url: myurl,
            contentType: 'json',
            type: "GET",
            data: JSON.stringify({ allItem }),
            success: function (response) {

            },
            error: function (xhr, status, error) {
                alert("error");
            }
        });

标签: javascriptajaxmodel-view-controller

解决方案


推荐阅读