Debug a script that sits in a partial view

2019-01-23 04:20发布

问题:

Why I can't debug scripts that reside in a partial view, that gets created in runtime? To see the script in the list of scripts (in Chrome for example) and debug it, I have to move it to the "regular" view on the upper level or I have to move it to a separate .js file. But what, if the script so small that I don't want to move it anywhere, and still want to be able to debug it?

回答1:

If you do not load the partial view via ajax (the view is in place at the initial page rendering) you can use 'debugger'. If the code you want to run is added to the dom IE will not know where the actual code is located that you want to debug. So:

// javascript
var foo = 2;
debugger;
// more javascript


回答2:

There's a much better way to do this now, just use the syntax

//@@ sourceURL=someValue

immediately after opening your script tag. Example:

<script type="text/javascript">
    //@@ sourceURL=_fooPartialView.cshtml
    function foo() {}
</script>

--edit--

Apparently due to some IE compatibility issue javascript source mapping has been changed from the above to:

//# sourceURL=_fooPartialView.cshtml

Also note, although not mentioned earlier, the @@ was only necessary for source mapping in razor views since "@" had other significance.



回答3:

It's generally considered poor practice to include a script inside of a partial view. You could run into all kinds of issues with multiple script references and performance. The better approach here is to ensure the script gets moved up to a placeholder in your head tag. For a few examples on this, check out:

Linking JavaScript Libraries in User Controls

and

Include JavaScript file in partial views

If you insist on loading the script from the partial, the 'debugger' approach above is very effective.