Tomas
Tomas

Reputation: 18097

Organize JS code in MVC app

I have several JS code in several partials Views.

I think it would be good idea to put all these code in separated JS file to separate JS code from HTML code.

But how do you deal with MVC code inside JS?

The example below is JS code which I have in partial View. I would like to put in into JS file but the JS code has MVC code @Url.Action("ResultForm", "File") and it will not be executed in JS file.

Any suggestion?

Javascript Code

<script type="text/javascript">
    var varTimerSpeed = 5000;
    var varTimerInterval;
    var onlyOneInstance = false;

    startTimer();

    function startTimer() {
        onlyOneInstance = false;
        varTimerInterval = setInterval(loadResultForm, varTimerSpeed);
    }

    function loadResultForm() {
        if (onlyOneInstance) return;
        clearInterval(varTimerInterval);
        onlyOneInstance = true;
        $.ajax({
            url: '@Url.Action("ResultForm", "File")',
            data: '',
            dataType: 'html',
            success: function (data) {
                $('#ResultForm').html(data);
                startTimer();
            }
        });
    };
</script>

Upvotes: 3

Views: 832

Answers (5)

Marcelo De Zen
Marcelo De Zen

Reputation: 9497

Create a file "somescript.js" and put the code inside a unique public function, extract hard-coded external dependencies and replace them for parameters.

var startXyz = function(resultFormUrl) {
    var varTimerSpeed = 5000;
    var varTimerInterval;
    var onlyOneInstance = false;

    startTimer();

    function startTimer() {
        onlyOneInstance = false;
        varTimerInterval = setInterval(loadResultForm, varTimerSpeed);
    }

    function loadResultForm() {
        if (onlyOneInstance) return;
        clearInterval(varTimerInterval);
        onlyOneInstance = true;
        $.ajax({
            url: resultFromUrl,
            data: '',
            dataType: 'html',
            success: function (data) {
                $('#ResultForm').html(data);
                startTimer();
            }
        });
    };
};

Then, in your page you do:

<script>
   $(function(){ 
       startXyz('@Url.Action("ResultForm", "File")');
   });
</script>

Now you have a modular function that will startup your page/partial and a script file that do not depends directly from server state and can be reused on the same or another page.

This approach is especially useful if a partial view is rendered more than once per page.

Upvotes: 0

Parv Sharma
Parv Sharma

Reputation: 12705

why dont you just create a partial view which contains nothing but js code
and do a renderpartial instead of adding a script tag?

Upvotes: 0

user1577895
user1577895

Reputation:

You can add hidden field with url:

// View:   
@Html.Hidden("LoadResultFormUrl", @Url.Action("ResultForm", "File"))

// js-file
function loadResultForm() {
    url = $("#LoadResultFormUrl").val();
    ...
};

Upvotes: 0

Amith George
Amith George

Reputation: 5916

I am assuming using a Razor partial for only the js code is not an option. In that case you could use this approach:

in your view.cshtml

<script type="text/javascript">
    var Namespace.urlForModule = '@Url.Action("ResultForm", "File")';
</script>
<script type="text/javascript" src="customScript.js"></script>

in you customScript.js

$.ajax({
    url: Namespace.urlForModule,
})

The idea is to separate out the Asp.Net MVC specific code from the js code.

The way you want to do that is upto you. As some one else suggested, you could attach data-* attributes to some div and read those. I prefer this, as it expresses my intent clearly.

Upvotes: 3

Ricardo Souza
Ricardo Souza

Reputation: 16446

A solution would be to create a meta tag or a data-* attribute with the desired dynamic value and catch it with JavaScript. This way you can separate the code entirely with minor changes.

Upvotes: 1

Related Questions