简体   繁体   English

在不使用模型的情况下将对象的JS数组传递给MVC控制器

[英]Passing JS array of objects to MVC controller without using a Model

I'm attempting to centralize one of the features in our application. 我正在尝试集中化应用程序中的功能之一。 Throughout the site we have a numerous areas where a user can export a table (Syncfusion Grid) as excel. 在整个站点中,我们有许多区域用户可以将表格(Syncfusion Grid)导出为ex​​cel。 One issue we have is that every time a user filters/sorts to maintain the new table data layout, in the event the user does want to export, we have to make a round trip to the server, poke the DB and run an accompanying script. 我们遇到的一个问题是,每当用户进行过滤/排序以维护新的表数据布局时,如果用户确实要导出,则我们必须往返于服务器,戳数据库并运行附带的脚本。 The alternative to this is we send out the filtered columns each time the user filters or on the export request. 替代方法是,每次用户过滤或在导出请求时,我们都会发送过滤出的列。

I'm currently trying to switch all these round trips in the latter most option of only sending the data when the request is made to alleviate some of the back and forth. 我目前正在尝试将所有这些往返行程切换为后一种选择,即仅在发出请求以减轻某些来回往返时才发送数据。 What I'd like to do is be able to send every grid to a single Controller which from the data can figure out what columns to show. 我想做的是能够将每个网格发送到单个控制器,该控制器可以从数据中找出要显示的列。 Every case I can find so far if a Controller accepting a List< MODELNAME > but if I follow this case I'm not sure if it will work. 到目前为止,每种情况下我都能找到控制器是否接受List < MODELNAME >的情况,但是如果我遵循这种情况,我不确定它是否会起作用。 I imagine I could create a generic export model which will accept the properties. 我想我可以创建一个接受属性的通用导出模型。 The caveat to this is that these tables are driven by the DB to limit the effort required to modify them if a requirements change. 需要注意的是,这些表由数据库驱动,以限制在需求发生变化时修改它们所需的工作。 Requirements are set by the reporting agencies our clients report to, neither us nor our clients so we never really know what will change. 要求是由我们的客户向我们报告的报告机构设定的,无论是我们还是我们的客户,因此我们永远不知道会发生什么变化。 Changing the tables returned in the stored procedure automatically updates the table on the front. 更改存储过程中返回的表会自动更新前面的表。 This would mean a change to the DB would need a subsequent update to the model if the property didn't previously exist. 这意味着如果该属性先前不存在,则对数据库的更改将需要对模型进行后续更新。

Enough background, I'm trying to sent a generic array to the MVC controller, during the POC I'm using an already existing feature and trying to modify it. 足够的背景知识,我正在尝试将通用数组发送到MVC控制器,在POC期间,我正在使用一个已经存在的功能并试图对其进行修改。

public void ExportAlertListToExcel(string name, List<object> grid, string ignore = "")

The data is sent to the server using the ajax below using jQuery 数据通过jQuery使用下面的Ajax发送到服务器

$.ajax({
        url: _url,
        type: "POST",
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ 'name': "Filler", 'grid': dataexport }),
        success: function (data) {
            // Do something neat
        },
        complete: function () { },
        error: function (e) {
            console.log(e);
        }
    });

The data will look something like 数据看起来像

[
{name: 'One', age: '10'},
{name: 'Two', age: '12'},
{name: 'Three', age: '14'},
{name: 'Four', age: '16'},
]

But when it hits the controller it the values will come back as just {object}, regardless of using List, Array, or IEnumerable. 但是,当它碰到控制器时,无论使用List,Array还是IEnumerable,其值都将作为{object}返回。 I've tried not stringifying the data being sent and stringifying the array of objects inside the array. 我试过不对发送的数据进行字符串化,也不对数组内的对象数组进行字符串化。 In cases where I get the data up its a string which I just cannot convert to an object where I can access the data values per item sent. 如果我得到的数据是字符串,则我不能将其转换为可以访问每个已发送项目的数据值的对象。 I feel this should be something trivial but I cannot seem to be able to wrap my head around how to go about it. 我觉得这应该是微不足道的,但是我似乎无法将头转向如何解决。 I've tried serializing, deserialzing, passing strings to try an access the data. 我尝试序列化,反序列化,传递字符串以尝试访问数据。

you have two primitive type parameter and one composite you may use custom route for your action like : controller/action/{name}/{ignore} and then reorder your parameter : 您有两个原始类型参数和一个复合类型,可以对操作使用自定义路由,例如:controller / action / {name} / {ignore},然后对参数重新排序:

public void ExportAlertListToExcel(string name , string ignore = "",object grid)

$.ajax({
    url: 'contrller/action?name=filler&ignore=c',
    type: "POST",
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: dataexport,
    success: function (data) {
        // Do something neat
    },
    complete: function () { },
    error: function (e) {
        console.log(e);
    }
});

after retrieving the object in your code cast it to list of object and work on it. 在代码中检索到对象后,将其强制转换为对象列表并对其进行处理。

JSON array data type is string. JSON数组数据类型为字符串。 Did you try this ? 你尝试过这个吗?

public void ExportAlertListToExcel(string grid)


$.ajax({
    url: 'contrller/action?name=filler&ignore=c',
    type: "POST",
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    data: dataexport,
    success: function (data) {
        // Do something neat
    },
    complete: function () { },
    error: function (e) {
        console.log(e);
    }
});

Try this, I have it working and binding as my custom object array in my controller 试试这个,我将它作为控制器中的自定义对象数组进行工作并绑定

  $('#costRowAdd').click(function () {
var shipmentCost = {
    CarrierName: $("#AgentCarrierID").val(),
    CostName: $("#ShipmentCostLineItems option:selected").html(),
    Quantity: $("#ShipmentCostqty").val().replace(',', ''),
    Rate: $("#ShipmentCostrate").val().replace('$', '').replace(',', ''),
    EstimatedCost: $("#ShipmentCostcharge").val().replace('$', '').replace(',', '')
}
var shipmentCosts = [];
shipmentCosts.push(shipmentCost);

$.ajax({
    url: 'AddShipmentCosts',
    type: 'POST',
    dataType: 'json',
    data: { ShipmentCosts: shipmentCosts, ShipmentNumber: $('#ShipmentNumber').val() },
    success: function (data) {

        LoadShipmentCosts($("#ShipmentNumber").val());
        $("#ShipmentCostqty").val('');
        $("#ShipmentCostrate").val('');
        $("#ShipmentCostcharge").val('');

    }
});

return false;

}); });

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

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