简体   繁体   中英

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. 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. 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.

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

The data is sent to the server using the ajax below using jQuery

$.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. 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 :

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. 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;

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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