Darren Young
Darren Young

Reputation: 11090

ASP.NET MVC Pass model from view into controller

I have the need to pass the current model of the view, from the view into a controller, upon a button click.

This is to export the current data to Excel.

What is the best way to do this? I keep trying to pass the Model from the view into a JS function as such:

onclick = "ExportToExcel(this.Model);"

But, the data is being passed into the JS as undefined. What am I doing wrong?

Thanks.

Upvotes: 0

Views: 1151

Answers (3)

sandeepKNJ
sandeepKNJ

Reputation: 23

The Model, after reaching the View from Controller (initially at the page load) is no longer accessible, I mean it sort of does not exist any more as an Object you can say. So, you cannot directly pass the model back to JS/Controller. If you want to pass any particular data from Model to JS, you can do so by actually "writing" the data in a hidden input and access this from Java Script using the input id by jQuery.

PS: I know this is pretty old question but I just wanted to know if I'm correct about this. :)

Upvotes: 1

Zote
Zote

Reputation: 5379

You can use jQuery to post your model object using and as @Raynos said, get download link. To do that, you'll to convert your model (cs/vb) to javascript.

Upvotes: 0

Raynos
Raynos

Reputation: 169373

the onclick code will get run in global scope so this === window.

I'd assume window.Model is undefined

Try

element.onclick = function() {
  ExportToExcel(this.Model);
};

For the record, exporting data to excel should be done on the server and should return a link to an excel file that get's temporary created on the server that users can download

Upvotes: 0

Related Questions