Optimal way to forward data selected from an Actio

2020-05-09 01:34发布

I'm not confident that the title is well put so feel free to criticize. :)

I have a controller that returns a page on which the user can click on some options creating a list of items (dynamically built up on the client using JS). As the user is satisfied, they can click on a button and then...

...currently, some DIVs are hidden/displayed, converting the (same) page to a read-only viewer of the selection.

...optimally, another ActionResult should be invoked presenting the information.

My biff is that I can't decide on a good way to transfer the data from one page to another: query string is one option, storing/retrieving to/from DB is an other. I'm not happy with any of these.

What would be a smooth and recommended way to transfer the data to a new view withing the same controller?

1条回答
男人必须洒脱
2楼-- · 2020-05-09 02:05
$.ajax({
    url: '@(Url.Action("Action", "Controller"))',
    type: 'post',
    data: {
        id: id,
        data1: data1
    },
    success: function (result) {
        if (result.Success) {
        }
});

A very simple way is like the above where you define as many fields as you want and as long as the input parameters match they will be received on the controller

public ActionResult Action(string id, string data1){...

if you want to get more complicated you can build lists and arrays with the json data and then it is usually a good idea to stringify it.

var data = {};
data.id = 'id';
data.list = [];
data.list.push({ name: 'name', location: 'location', etc })

then in the ajax call

data: Json.stringify(data),

again, as long as the names match the controller will receive it. Hope this helps

Edit: Json.stringify is a tool that is used for sending the data. I don't know all of the details of what it does but it is recommended to use for more complex data. The example here I used for sending a model back to the controller but you mentioned not wanting to create a model. I believe to receive this data on the controller side you need to have input parameters that match what is defined in data. From what I have above list is a complex type so your controller would be something like this.

Public ActionResult Action(string id, List<ComplexType> list){...
查看更多
登录 后发表回答