user3397240
user3397240

Reputation: 239

Run javascript code that is specific to the view

In my ASP.NET MVC4 application I got 1 javascript file for my functions across the site. This works pretty good - however I want to run certain code in certain views. Usually I would solve this by simply putting a short script tag in the view calling the desired function. However I load my js files at the bottom of the body tag so this script tag would call a function before it being loaded which would obviously not work.

How can I call individual parts of my js file from different views while keeping my js files at the bottom of the body?

Upvotes: 0

Views: 227

Answers (3)

darkchico
darkchico

Reputation: 647

I'm detailing the answer given by Matt in his comment : in your layout, you can specify that you want some additional HTML content (in your case, that will be your JS). You'll want to add it after your main JS block.

@RenderSection("AddScripts", required: false)

Then in your view, you can add a section and it won't be rendered in the view, but in the corresponding section in the layout (after your main JS block).

@section AddScripts {
<script type="text/javascript">
 ...
</script>
}

Upvotes: 0

beautifulcoder
beautifulcoder

Reputation: 11340

My approach is to tag said views with an id:

<div id="specific-page-name"></div>

Then in my javascript simply do:

if ($('#specific-page-name').length) {
    // Run code
}

This way you can still separate your views from js code.

Finally, if I have to use model data in js I can do something like:

<div data-model-data="@Model.Data"></div>

And simply read it as:

$('div').data('model-data');

Upvotes: 0

Erstad.Stephen
Erstad.Stephen

Reputation: 1035

There are a few things going on here.

  1. I would not be putting JavaScript directly in the page. Many reasons for this, and is not the focus of your question, but something I wanted to bring up.

  2. You can have a separate JS file that gets loaded after your main JS file that actually does the call to the functions from "main".

Upvotes: 1

Related Questions