My .cshtml file in Visual Studio looks like this:
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.
My .cshtml file in Visual Studio looks like this:
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.
- Good question, I've noticed that VS doesn't quite have the collapsing figured out in js yet. It might work if you collapse the file and then open it again. – asven Commented Jul 2, 2014 at 15:29
- @asven No, unfortunately that didn't work. – Lincoln Bergeson Commented Jul 2, 2014 at 15:33
- I think the better question might be, why do you need to use Razor syntax in a function definition? Things like URLs should be configuration, where you have one Razor view that basically spits out a JavaScript object literal. – Greg Burghardt Commented Jul 2, 2014 at 15:38
- @GregBurghardt How would I access said Razor view from a JS function? – Lincoln Bergeson Commented Jul 2, 2014 at 15:38
- You don't need to. The Razor view is just part of the regular page. It creates a JavaScript literal, which you can then reference from your function. I'm going to post an answer in a few minutes to show you what I mean. – Greg Burghardt Commented Jul 2, 2014 at 15:52
2 Answers
Reset to default 6To expand on my ment.
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 pletely 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.
Also you can highlight the block and press ctrl + m, ctrl + h to collapse the block