javascriptasp.netservertag

ASP.NET inline server tags


I'd like to start by saying that my code is working perfectly, this is more a "how best to do it" kind of question.

So I have code like this in my .aspx file:

    function EditRelationship() {
        var projects=<%= GetProjectsForEditRelationship() %>;

        // fill in the projects list
        $('#erProjectsSelect').empty();
        for(var i in projects)
            $('#erProjectsSelect').append('<option value='+projects[i][0]+'>'+projects[i][1]+'</option>');

        var rels=<%= GetRelationshipsForEditRelationship() %>;

        // etc
    }

Again, it's working fine. The problem is that VS2008 kinda chokes on code like this, it's underlining the < character in the tags (with associated warnings), then refusing to provide code completion for the rest of the javascript. It's also refusing to format my document anymore, giving parsing errors. The last part is my worst annoyance.

I could put some of these in evals I guess, but it seems sorta dumb to add additional layers and runtime performance hits just to shut VS up, and it's not always an option (I can't remember off the top of my head where this wasn't an option but trust me I had a weird construct).

So my question is, how do you best write this (where best means fewest VS complaints)? Neither eval nor ajax calls fit this imo.


Solution

  • If your aim is to reduce VS complaints, and if you are running asp.net 4 (supporting Static client Ids), maybe a strategy like the following would be better?

    1. Create a ASP:HiddenField control, set its ClientIdMode to "Static"
    2. Assign the value of GetRelationshipsForEditRelationship() to this field on page load
    3. In your javascript, read the value from the hidden field instead, I assume you know how to do this.

    It's more work than your solution, and you will add some data to the postback (if you perform any) but it won't cause any VS complaints I guess :)