Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't Visual Studio collapse Javascript functions that include Razor syntax?

My .cshtml file in Visual Studio looks like this:

enter image description here

Notice how createTabStrip can collapse, but createTeachersTab cannot. Why is this?

EDIT: It seems to have something to do with the razor syntax. I took out all of the @ signs and createTeachersTab was able to collapse.

like image 653
Lincoln Bergeson Avatar asked Jul 02 '14 15:07

Lincoln Bergeson


1 Answers

To expand on my comment.

You generally do not want to define functions in your Razor views. Instead, define them and import them from an external JavaScript file. If you need info from C# in JavaScript, you could create a global config object in JavaScript in a Razor partial, then render that partial.

function_lib.js

function createTeachersTab() {
    ...
        read: {
            url: config.teachers.newTabUrl
        }
    ...
}

Views/Shared/_JavaScriptConfig.cshtml

This would be rendered as a Partial in the <head> of the HTML document.

<script type="text/javascript">
    var config = {
        teachers: {
            newTabURL: '@Url.Action("Teachers", "Users")'
        }
    };
</script>

Then anywhere else in your JavaScript, you can reference these settings via the global config JavaScript variable.

config.teachers.newTabUrl

Edit: I also completely recognize that this does not solve the code collapsing problem in Visual Studio, which appears to be a parsing bug on their end. The real solution is "Don't define JavaScript functions in Razor views" as this is considered bad practice.

like image 127
Greg Burghardt Avatar answered Sep 17 '22 12:09

Greg Burghardt