For a new project, I'm using a javascript / jquery suite to display charts ( http://www.highcharts.com). The javascript code for each page is roughly the same, so I wanted to centralize it and make something reusable. I'm using ASP.NET MVC for this application so I was looking to creating a servercontrol with some settings which would output the javascript / jQuery code in an organized way. But I'm not sure on how to do this in a neat way. Of course I could just go off and build a long string and render that to the page, but that seems rather ugly.
So I'm basically looking for best pratices on how to convert a piece of javascript into a managable servercontrol. I also want to include things like automatic databinding to JSON webservices.
Update; I've created a model which I want to use for the charting. It contains things like axis labels, chart title and stuff like that.
Now in my page, I have the jQuery code which contains things like this:
title: { text: '<%: Model.Title %>' },
to set the various chart properties. But I understand that this is not good practice, I'm just not sure on what is. In the above example, I want to do things like add the title property when it's set in my model but completely omit it when it's not (which is not happening now). I can get there by adding a lot of if/else stuff, but that's not going to make things prettier. Therefore I'm wondering out loud wether the constructing of the jquery code isn't something that should be done in a class instead.
I would recommend placing the javascript in a .js file and simply reference it with a script tag from the MVC master view, page view or user control view were you need it. There are a couple of advantages in placing javascript in a separate file and it is considered a good practice. Caching of the javascript content in the browser will enhance performance and reduce the use of bandwidth – and it will be easier to debug the javascript with firebug or any other javascript debugger.
In MVC DisplayTemplates or partial views are more analogous to controls than HtmlHelpers. If its just script that doesn't require any additional data lookups or things like that, I would just use a Partial view and reference with @Html.Partial. If it has additional functionality / security / data lookup, then I would go with a child action (ie. create a ChartController and reference with @Html.Action("ActionName", "Chart", params). If its based upon a property in your model, then I would go with a DisplayTemplate.
If its entirely client side though with just a data request, I would definitely do what is recommended by Marquez and just have a .js file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With