views:

122

answers:

1

Hi,

The question is how to create controls/partial views/edittemplates (ascx files) in ASP.Net MVC2 so that they are "self-containing". Self-containing means here that if some Javascript code should be applied on the control, that's not included in the page (aspx), but in the control itself. Specific example: NerdDinner's DateTime.ascx. The file contains the JS code which makes the textbox a nice DateTime picker.

My problems: The containing page has the jQuery.js, the timepicker.js, the jQueryUI's css and the datepicker's css. (In case of NerdDinner these all are in the master page). So whenever I'd like to use the fancy DateTimePicker for my DateTime types, the containing page has to be aware of these dependencies and has to add all the js and css files. I think what I miss here is a solution which replaces the ClientScript.RegisterClientScriptBlock.

Other problem with the same NerdDinner example: In the DateTime.ascx it says $('#Dinner_EventDate') which is a dependency both on the container type and on the property name. That's not a general solution for a DateTime shared EditorTemplate.

Any suggestions?

A: 

You need to link to these files from the page. Doing otherwise will be hacking your way against the way these elements are included in html vs. where your control is included in the page.

What we do is we join all these separate js/css files into a single file with some extra code (done once). That way you only link to the single file from your master page. As long as you don't have anything particularly heavy in there that's very reasonable.

For the id issue, change the jquery to search by css class.


original answer: ignore below, I thought it wasn't already in separate files.

Move it to a .js file, and change from using the id to use a class.

If you want to keep it structured / the .js code that's on a file dedicated to only that control's code, you can do so and add some extra code that joins all the various .js files in your site to a single .js file. This allows you to structure it as you please, without getting unnecessary extra requests.

eglasius
That's not a solution. I don't want to download all the js code for all the pages (even if cached), because in 99% of the page visits just about 20% of the code is used. The same as with nerddinner: the datetime picker is used just when you add or edit a new dinner. But most visits are not for adding/editing, so they don't need that code at all. On a more complex page you might have several similar components. CKEditor more than 300K, and read-only users won't need that ever. 300K is something I don't want to unnecesairly download.
foldip