2

I'm using ASP.NET MVC 2 and stuck with the situation when needed to store all javascripts in separate javascript files.
But in some pages Javascript's contains information from server-side, so I need a way to do something like this.

I want to make separate JS files and include them in Site.Master. But still I want to make workable code blocks like this

loadNews("<%= Model.A%>", "<%= Model.B%>");

Is there any way to do some trick?

3 Answers 3

4

I'm a newbie on MVC and also facing that situation. I'm dealing with it by calling the javascript functions via a script block on the view.

Something like this:

--On MyFile.js

function loadNews(a, b) {
   //Do fun stuff
}

--On Index.cshtml

<script type="text/javascript">
   loadNews("<%= Model.A%>", "<%= Model.B%>");
</script>

Another option could be declare the variables on the view's script block and referencing those variables on the javascript, since their scope would be global. Would be an ugly thing and a bit harder to mantain, but also could do the job. Like this:

--On MyFile.js

function loadNews() {
   doSomethingWithA(a);
   doSomethingElseWithB(b);
}

--On Index.cshtml

<script type="text/javascript">
   var a = "<%= Model.A%>";
   var b = "<%= Model.B%>";
</script>
Sign up to request clarification or add additional context in comments.

Comments

4

We had the same issue previous and found a nice solution using jQuery.

Firstly, we extend jQuery with our own namespace (we placed the following in a separate JS file and included it on the masterpage):

$.extend({
    myProject: {            
        dataitem: {},
        dataitems: function (a) {
            $.extend($.myProject.dataitem, a);
        }
    }
});

Now, whenever we have a value that we want to pass to our JS file from the ASP view, we simply add the following to the view:

<script type="text/javascript">            
        $.myProject.dataitems({   
            foo: Model.Bar,   
            bar: Model.Foo
        });
</script> 

Now, for your separate JS file (which would be included below the aforementioned <script></script> block) accessing the value is simple:

$('#foo').click(function () {
    alert($.myProject.dataitem.foo);
});

1 Comment

How is it better than Andreson's solution which uses variables? Is it because that way you create global variables? However, aren't these dataietems global as well?
1

Can you put the data in hidden fields, then access them with Javascript?

<%= Html.HiddenFor(x => x.A) %>

loadNews($('#A').val());

EDIT: Sorry, MVC2

Comments

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.