1

I have some javascript and c# code inside one of my views that is deeply nested. Heres the general structure something like this:

@if(something)
{
    <script type="text/javascript">
          @if(something_else)
          {  
                <text>
                    ...some javascript...
                    event: function(){
                       @ViewBag.Property = value;
                    }
                    ...some more javascript... 
                </text>
          }
          @else if(something_else_else)
          {
                 ...some more javascript...
          }
    <script>
}

It works fine in the html file but I would like to put it in an external js file and instead just load like this:

@if(something)
{
    <script type="text/javascript" src="@Url.Content("~Scripts/thescript.js")"></script>
}

However if I try to do this I get error: missing } in XML expression

I tried wrapping the contents in but it still complains with same error. Anybody know if this is possible because its a rather long script and making my view very convoluted.

1
  • See Eric's answer. Use partial views instead of js file. Commented Mar 25, 2012 at 6:51

2 Answers 2

4

You can use @Html.RazorJSInclude("scriptSource"). Please see the following link

http://djsolid.net/blog/razorjs---write-razor-inside-your-javascript-files

Sign up to request clarification or add additional context in comments.

Comments

2

If I understand you correctly, you're putting code that includes Razor markup in an external .JS file.

The Razor view engine does not parse content in .JS files, so it would not work as you describe.

However, you can greatly clean up your code by using Partial Views where repetitive Razor markup occurs in your view.

1 Comment

Ah, yes I dont know how I overlooked to use a partialview. It worked only when wrapped in text blocks like such: <text>@Html.Partial("_PartialView", null)</text> Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.