Wellington Zanelli
Wellington Zanelli

Reputation: 1964

Insert scripts at the end of page using Html Helper

I have an Html Helper that generates a simple HTML table. I want to generate, in the same helper, some scripts to work on this table, like edit rows, reorder etc.

I already have these scripts, my question is:

How can I generate these scripts by my HTML Helper and put then at the end of the page?

I currently added the scripts at the end of html table, like an single string (Html of the table and the scripts) and printed it on the page, is there a better way to do this, any best practice for solve this problem?

For make the question clearer, here's my signature of the helper:

public static MvcHtmlString CustomTableRepository
       (this HtmlHelper html, string idTable, Hashtable columns, string jsonRepo)

Where:

idTable: Id of the tag table
columns: The key/value of each th cell of the columns
jsonRepo: jSon repository, where I will take the values of my table and draw it

Upvotes: 2

Views: 533

Answers (1)

monkeyhouse
monkeyhouse

Reputation: 2896

This doesn't sound particularly bad, the only downsides are 1. it won't get minified 2. if you have more than one table you have duplicate scripts 3. it won't get cached so it will be sent each time a page loads

EDIT: new suggestion

Create and add a list to the viewbag. In your html helpers, add scripts you need into this list. At the end of your layout, use linq to select the unique script names, and render them.

OLD SUGGUESTION - read if you want. it contains okay practices.

if the table is used on most pages, just put it in your scripts folder and include it in your layout.

if its only used on a few page, you're going to want to keep it in the helper. you can always move the script into your scripts folder, like into Scripts > Elements > Table.js . This might make some sense. Then inlcude it in your helper by way of a function. Like if your using jquery, you can write the text

<script> $(function(){ $.getScript("Scripts/Element/Table.js") }); </script>

Upvotes: 3

Related Questions