0

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.

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

4 Comments

Thanks for the answer. I have tried this, both with quote marks and without, and the function does not now get called. Also, the excel exporting willbe doneon the server, I just need to get the data to the controller/javascript and then it will be passed onto the Model class on the server to do the logic.
@DarrenYoung your supposed to use JavaScript to attach the onclick function handler to the element, not add it as an attribute in the HTML
Thanks, I have it recognising the command now. But it still won't recognise this.Model. Sorry for obvious questions, I'm new to MVC asp.net. Thanks.
@DarrenYoung I also made the mistake of thinking this would fix your problem. I dont know enough about asp.net mvc off hand to see where the Model lives in the javascript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.