简体   繁体   中英

How to pass a Javascript Array to a View ? (MVC4)

I am using the jquery datatables in one of my views and want to generate a report with the result of the filtred data, so to generate the report the simplest solution i could come up with was to generate a pdf file (in a view), anyway, to get the filtred results i use the following method :

myDataTableHandle = $('#example1').dataTable(...);
var myFilteredRows = myDataTableHandle._('tr', {"filter":"applied"});

To open a view from a js file through a click i found that i could use something like :

function foo(id) {
    var url = '@Url.Action("Details", "Branch", new { id = "__id__" })';
    window.location.href = url.replace('__id__', id);
}

Now i am wondering if there is a way to pass a js Array to an MVC view, in other words myFilteredRows, or of there is another way to pass the filtred result to the controller and then from there call the view?

I hope my question is clear

Looks to me like you have a gap in understanding how this thing works. In the js code you wrote (foo(id)) you are not calling the view, you are making a request to the server side, so this is passing through the controller (action method branch is getting called -- put a breakpoint there to check) and then the the action method is calling the view and it gets returned to you on the client side.

Also in the function you are passing id parameter to the controller action method, you can same way pass your array as a string, but you will need to update the signature on the controller for that action method.

public ActionResult Branch(int id, string array)

Then you will need to edit your view to accept this array from the controller, either by adding it to the view bag

ViewBag.array = array

Or you can add it to your model, if the branch view is accepting a model. In the view you will have to define an array in a js block to accept this, something like this (this will probably not work as is, you have to debug the js in browser until you get it right)

var array = [@ViewBag.array];

The view is an MVC term for HTML content, and it is someting that we deal with on the server side, your controllers work with the views with the help of MVC framework to pass data from the controller to the view. When you talk about client side, speaking of the view now becomes vague. I hope you understand the point.

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